Something went wrong. Try again.
A free, open-source, self-hosted place to write a novel.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335import { and, desc, eq, isNotNull, isNull, sql } from 'drizzle-orm';import { db, tables } from './db/index.ts';import { insertIndexedScene, lastOpenedScene } from './manuscript.ts';import { clearProject, indexNote, reindexBook } from './search.ts';
/** * The Digital Rust failure accents that storylines and note types share, worn on * a project card. */export const PROJECT_ACCENTS = [ { value: 'rust', label: 'Rust' }, { value: 'dead-thread', label: 'Dead Thread' }, { value: 'stack-overglow', label: 'Stack Overglow' }, { value: 'blue-screen', label: 'Blue Screen' }, { value: 'fractured-shell', label: 'Fractured Shell' }, { value: 'memory-leek', label: 'Memory Leek' }, { value: 'thermal-throttle', label: 'Thermal Throttle' }] as const;
export const DEFAULT_PROJECT_ACCENT = 'rust';
export type ProjectDetails = { title: string; subtitle?: string; description?: string; author?: string; accent?: string;};
export class ProjectDetailsError extends Error { constructor(message: string) { super(message); this.name = 'ProjectDetailsError'; }}
const MAX_TITLE = 120;const MAX_SUBTITLE = 160;const MAX_AUTHOR = 120;const MAX_DESCRIPTION = 600;
export type ProjectCard = { role: 'owner' | 'co_author' | 'reader'; id: string; title: string; subtitle: string | null; description: string | null; author: string | null; accent: string; isExample: boolean; updatedAt: Date; books: number; scenes: number; words: number; /** The scene left open last, so the card resumes it instead of starting over. */ resumed: ReturnType<typeof lastOpenedScene>; /** * The file the project was imported from, and whether this instance still * holds a copy. Null for a project that was never imported. */ importedFrom: { name: string; source: boolean } | null;};
/** * Totals are computed in SQL rather than loaded and summed, so a project with a * hundred thousand words still opens the library instantly. */export function listProjects(ownerId: string): ProjectCard[] { const rows = db .select({ id: tables.project.id, role: tables.projectMember.role, title: tables.project.title, subtitle: tables.project.subtitle, description: tables.project.description, author: tables.project.author, accent: tables.project.accent, isExample: tables.project.isExample, updatedAt: tables.project.updatedAt, books: sql<number>`( select count(*) from ${tables.book} where ${tables.book.projectId} = ${tables.project.id} and ${tables.book.deletedAt} is null )`, scenes: sql<number>`( select count(*) from ${tables.scene} join ${tables.chapter} on ${tables.chapter.id} = ${tables.scene.chapterId} join ${tables.book} on ${tables.book.id} = ${tables.chapter.bookId} left join ${tables.part} on ${tables.part.id} = ${tables.chapter.partId} where ${tables.book.projectId} = ${tables.project.id} and ${tables.scene.deletedAt} is null and ${tables.chapter.deletedAt} is null and ${tables.book.deletedAt} is null and ${tables.part.deletedAt} is null and (${tables.chapter.partId} is null or ${tables.part.bookId} = ${tables.book.id}) )`, importedName: tables.importReport.sourceName, importedSource: tables.importReport.sourceId, words: sql<number>`coalesce(( select sum(${tables.scene.wordCount}) from ${tables.scene} join ${tables.chapter} on ${tables.chapter.id} = ${tables.scene.chapterId} join ${tables.book} on ${tables.book.id} = ${tables.chapter.bookId} left join ${tables.part} on ${tables.part.id} = ${tables.chapter.partId} where ${tables.book.projectId} = ${tables.project.id} and ${tables.scene.deletedAt} is null and ${tables.chapter.deletedAt} is null and ${tables.book.deletedAt} is null and ${tables.part.deletedAt} is null and (${tables.chapter.partId} is null or ${tables.part.bookId} = ${tables.book.id}) ), 0)` }) .from(tables.project) .innerJoin(tables.projectMember, eq(tables.projectMember.projectId, tables.project.id)) .leftJoin(tables.importReport, eq(tables.importReport.projectId, tables.project.id)) .where(and(eq(tables.projectMember.userId, ownerId), isNull(tables.project.deletedAt))) .orderBy(sql`${tables.project.updatedAt} desc`) .all();
return rows.map(({ importedName, importedSource, ...row }) => ({ ...row, books: Number(row.books), scenes: Number(row.scenes), words: Number(row.words), resumed: lastOpenedScene(row.id), importedFrom: importedName === null ? null : { name: importedName.trim() || 'the imported file', source: importedSource !== null } }));}
export function createProject(ownerId: string, title: string): string { const id = crypto.randomUUID(); const now = new Date();
db.transaction((tx) => { tx.insert(tables.project).values({ id, ownerId, title, createdAt: now, updatedAt: now }).run();
tx.insert(tables.projectMember) .values({ id: crypto.randomUUID(), projectId: id, userId: ownerId, role: 'owner', createdAt: now }) .run();
// A new project starts with a book, a chapter and a scene, so the writer lands // on a page they can type into instead of a form. const bookId = crypto.randomUUID(); const chapterId = crypto.randomUUID();
tx.insert(tables.book) .values({ id: bookId, projectId: id, title: title, ordinal: 0, createdAt: now, updatedAt: now }) .run();
tx.insert(tables.chapter) .values({ id: chapterId, bookId, title: 'Chapter 1', ordinal: 0, createdAt: now, updatedAt: now }) .run();
insertIndexedScene(tx, { chapterId, title: 'Scene 1', ordinal: 0, createdAt: now, updatedAt: now }); });
return id;}
/** * Gives every project's owner a membership row, because access is decided from * that row: a project whose row is missing, such as one written by an older * build, is invisible to its own owner. Runs at boot, and costs one scan of the * project table on a consistent instance. */export function ensureOwnerMembership() { const orphans = db .select({ projectId: tables.project.id, ownerId: tables.project.ownerId }) .from(tables.project) .where( sql`not exists ( select 1 from ${tables.projectMember} where ${tables.projectMember.projectId} = ${tables.project.id} and ${tables.projectMember.userId} = ${tables.project.ownerId} )` ) .all();
for (const row of orphans) { db.insert(tables.projectMember) .values({ id: crypto.randomUUID(), projectId: row.projectId, userId: row.ownerId, role: 'owner', createdAt: new Date() }) .onConflictDoNothing() .run(); }}
/** * The caller has already checked that this writer can write to the project. An * empty field is stored as null, because every reader tests for null to decide * whether it has something to show. */export function updateProjectDetails(projectId: string, input: ProjectDetails) { const title = input.title.trim().slice(0, MAX_TITLE);
if (title.length === 0) throw new ProjectDetailsError('A project needs a name.');
db.update(tables.project) .set({ title, subtitle: field(input.subtitle, MAX_SUBTITLE), description: field(input.description, MAX_DESCRIPTION), author: field(input.author, MAX_AUTHOR), accent: readAccent(input.accent), updatedAt: new Date() }) .where(eq(tables.project.id, projectId)) .run();}
function field(value: string | undefined, max: number): string | null { const text = (value ?? '').trim().slice(0, max);
return text.length > 0 ? text : null;}
function readAccent(value: string | undefined): string { const known = PROJECT_ACCENTS.find((accent) => accent.value === value);
return known?.value ?? DEFAULT_PROJECT_ACCENT;}
/** * The caller has already checked that this writer owns the project, because * deleting takes it from everyone else in it. */export function deleteProject(projectId: string) { db.transaction(() => { db.update(tables.project) .set({ deletedAt: new Date() }) .where(eq(tables.project.id, projectId)) .run(); clearProject(projectId); });}
/** * The caller has already checked ownership and that the project is in the trash. * Membership and child rows cascade from the project row. Upload files stay on * disk until `prune-uploads` runs, because a copy can share an image id. */export function purgeProject(projectId: string) { db.transaction(() => { const project = db .select({ deletedAt: tables.project.deletedAt }) .from(tables.project) .where(eq(tables.project.id, projectId)) .get();
if (!project?.deletedAt) { throw new Error('Only a project in the trash can be deleted forever.'); }
clearProject(projectId); db.delete(tables.project).where(eq(tables.project.id, projectId)).run(); });}
export function listDeletedProjects(userId: string) { return db .select({ id: tables.project.id, title: tables.project.title, deletedAt: tables.project.deletedAt }) .from(tables.project) .innerJoin(tables.projectMember, eq(tables.projectMember.projectId, tables.project.id)) .where( and( eq(tables.projectMember.userId, userId), eq(tables.projectMember.role, 'owner'), isNotNull(tables.project.deletedAt) ) ) .orderBy(desc(tables.project.deletedAt)) .all();}
export function restoreProject(projectId: string) { db.transaction(() => { db.update(tables.project) .set({ deletedAt: null, updatedAt: new Date() }) .where(eq(tables.project.id, projectId)) .run();
for (const book of db .select() .from(tables.book) .where(eq(tables.book.projectId, projectId)) .all()) { reindexBook(book.id); } for (const note of db .select() .from(tables.note) .where(eq(tables.note.projectId, projectId)) .all()) { indexNote(note.id); } });}