Something went wrong. Try again.
A free, open-source, self-hosted place to write a novel.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468import { and, eq, isNull } from 'drizzle-orm';import { db, tables } from '#lib/server/db/index.ts';import { prepareDocumentBody } from './document.ts';import { insertIndexedScene } from './manuscript.ts';import { indexNote } from './search.ts';import { defaultNoteTypes } from './note-types.ts';import type { MatterPosition } from '#lib/matter.ts';import prose from '#lib/server/fixtures/example/book.json';import { EXAMPLE, type ExampleChapter, type ExampleScene} from '#lib/server/fixtures/example/manifest.ts';
type SeedScene = ExampleScene & { paragraphs: string[];};
type SeedChapter = Omit<ExampleChapter, 'chapter' | 'scenes'> & { title: string; matter?: MatterPosition | null; scenes: SeedScene[];};
/** * The example project, so a new writer's library is not an empty room. The * words are L. Frank Baum's 1900 novel, in the public domain: * `fixtures/example/book.json` holds the prose and * `fixtures/example/manifest.ts` the parts, scenes, storylines and notes around * it. */
/** Chapter prose, by title, so a manifest entry finds its own words. */const PROSE = new Map(prose.chapters.map((chapter) => [chapter.title, chapter.paragraphs]));
export type SeedResult = 'created' | 'exists';
const SEED_NOTE_KEYS: Record<string, string> = { Character: 'character', Place: 'place', Object: 'thing', Idea: 'idea'};
type Tx = Parameters<Parameters<typeof db.transaction>[0]>[0];type ProjectReader = Pick<typeof db, 'select'> | Pick<Tx, 'select'>;
function findExampleProject(ownerId: string, reader: ProjectReader = db): string | null { return ( reader .select({ id: tables.project.id }) .from(tables.project) .where( and( eq(tables.project.isExample, true), eq(tables.project.ownerId, ownerId), isNull(tables.project.deletedAt) ) ) .limit(1) .get()?.id ?? null );}
/** * The guard asks whether a live sample exists in this writer's library, not * whether the instance was ever seeded: the sample is soft-deleted, and one * writer's copy neither fills another's library nor blocks their own re-add. * Checked inside the transaction so concurrent first opens create one copy. */export function seedExampleProject(ownerId: string): SeedResult { return db.transaction((tx) => { if (findExampleProject(ownerId, tx)) return 'exists';
const projectId = crypto.randomUUID(); const now = new Date();
tx.insert(tables.project) .values({ id: projectId, ownerId: ownerId, title: EXAMPLE.project.title, subtitle: EXAMPLE.project.subtitle, description: EXAMPLE.project.description, author: EXAMPLE.project.author, accent: EXAMPLE.project.accent, isExample: true, createdAt: now, updatedAt: now }) .run();
tx.insert(tables.projectMember) .values({ id: crypto.randomUUID(), projectId, userId: ownerId, role: 'owner', createdAt: now }) .run();
// Storylines first: a scene references one by title. const storylineIds = new Map<string, string>();
for (const [index, line] of EXAMPLE.storylines.entries()) { const id = crypto.randomUUID(); storylineIds.set(line.title, id); tx.insert(tables.storyline) .values({ id, projectId, title: line.title, accent: line.accent, ordinal: index, createdAt: now, updatedAt: now }) .run(); }
/* * Note types and templates come from the same list a new project gets, so the * example stays in sync with fresh projects. */ const typeIds = new Map<string, string>();
for (const [index, kind] of defaultNoteTypes().entries()) { const id = crypto.randomUUID(); const key = SEED_NOTE_KEYS[kind.name]; if (key) typeIds.set(key, id); tx.insert(tables.noteType) .values({ id, projectId, name: kind.name, pluralName: kind.pluralName, accent: kind.accent, template: kind.template, ordinal: index }) .run(); }
const noteIds = new Map<string, string>();
for (const [index, note] of EXAMPLE.notes.entries()) { const id = crypto.randomUUID(); const prepared = prepareDocumentBody({ type: 'doc', content: markdownToDoc(note.body) }); noteIds.set(note.title, id); tx.insert(tables.note) .values({ id, projectId, noteTypeId: typeIds.get(note.kind) ?? null, title: note.title, summary: note.summary, body: prepared.body, bodyText: prepared.bodyText, ordinal: index, createdAt: now, updatedAt: now }) .run(); }
/* * The seed writes rows directly, so it indexes them too. Rows are inserted * first because the index readers look the row up, and all of it shares the * outer transaction, so a failed seed leaves no index entries behind. */ for (const noteId of noteIds.values()) { indexNote(noteId); }
const bookId = crypto.randomUUID();
tx.insert(tables.book) .values({ id: bookId, projectId, title: EXAMPLE.project.title, ordinal: 0, createdAt: now, updatedAt: now }) .run();
/* * Matter pages live on the book, not a part, and their ordinals count * within their own front or back group. They are written before and after * the parts, in the order they read. */ const writeMatter = (position: MatterPosition) => { const pages = EXAMPLE.matter.filter((page) => page.position === position);
for (const [index, page] of pages.entries()) { const paragraphs = PROSE.get(page.chapter); if (!paragraphs) { throw new Error(`The example manuscript has no chapter "${page.chapter}".`); }
writeChapter( tx, bookId, null, { title: page.chapter, matter: position, synopsis: page.synopsis, storyline: page.storyline, card: page.card, scenes: splitChapterProse(page.chapter, paragraphs, page.scenes) }, index, storylineIds, noteIds, now ); } };
writeMatter('front');
for (const [partIndex, part] of EXAMPLE.parts.entries()) { const partId = crypto.randomUUID();
tx.insert(tables.part) .values({ id: partId, bookId, title: part.title, ordinal: partIndex, createdAt: now, updatedAt: now }) .run();
for (const [chapterOrdinal, entry] of part.chapters.entries()) { const paragraphs = PROSE.get(entry.chapter);
/* * A typo in either list must not write the wrong prose under the wrong * title. `seed.spec.ts` seeds the example, so this fails in tests before * it can fail on somebody's first sign-in. */ if (!paragraphs) { throw new Error(`The example manuscript has no chapter "${entry.chapter}".`); }
writeChapter( tx, bookId, partId, { title: entry.chapter, kind: entry.kind, synopsis: entry.synopsis, storyline: entry.storyline, card: entry.card, scenes: splitChapterProse(entry.chapter, paragraphs, entry.scenes) }, chapterOrdinal, storylineIds, noteIds, now ); } }
writeMatter('back'); return 'created' as const; });}
/** * Returns this writer's live example project id, seeding a fresh copy first if * none is currently in their library. */export function ensureExampleProject(ownerId: string): string { seedExampleProject(ownerId); const id = findExampleProject(ownerId); if (!id) throw new Error('Example project could not be created.'); return id;}
function splitChapterProse( chapterTitle: string, paragraphs: string[], scenes: ExampleScene[]): SeedScene[] { const starts = scenes.map((scene, index) => { if (index === 0) return 0; const prefix = scene.startsWith; if (!prefix) { throw new Error(`Scene "${scene.title}" in "${chapterTitle}" has no startsWith marker.`); } const found = paragraphs.findIndex((paragraph) => paragraph.startsWith(prefix)); if (found <= 0) { throw new Error( `Scene "${scene.title}" in "${chapterTitle}" found no paragraph starting with "${prefix}".` ); } return found; });
return scenes.map((scene, index) => ({ ...scene, paragraphs: paragraphs.slice(starts[index], starts[index + 1]) }));}
function writeChapter( tx: Tx, bookId: string, partId: string | null, seedChapter: SeedChapter, ordinal: number, storylineIds: Map<string, string>, noteIds: Map<string, string>, now: Date) { const chapterId = crypto.randomUUID();
tx.insert(tables.chapter) .values({ id: chapterId, bookId, partId, title: seedChapter.title, synopsis: seedChapter.synopsis, kind: seedChapter.matter ? 'section' : (seedChapter.kind ?? 'chapter'), matter: seedChapter.matter ?? null, ordinal, createdAt: now, updatedAt: now }) .run();
if (seedChapter.storyline) { const chapterStorylineId = storylineIds.get(seedChapter.storyline); if (!chapterStorylineId) { throw new Error(`Unknown storyline "${seedChapter.storyline}" on "${seedChapter.title}".`); }
tx.insert(tables.plotCard) .values({ id: crypto.randomUUID(), storylineId: chapterStorylineId, chapterId, title: seedChapter.title, body: seedChapter.card ?? seedChapter.synopsis, ordinal, createdAt: now, updatedAt: now }) .run(); }
for (const [sceneIndex, seedScene] of seedChapter.scenes.entries()) { const storylineId = seedScene.storyline ? (storylineIds.get(seedScene.storyline) ?? null) : null;
if (seedScene.storyline && !storylineId) { throw new Error(`Unknown storyline "${seedScene.storyline}" on "${seedScene.title}".`); }
const sceneId = insertIndexedScene(tx, { chapterId, title: seedScene.title, synopsis: seedScene.synopsis, viewpoint: seedScene.viewpoint, status: seedScene.status, body: { type: 'doc', content: seedScene.paragraphs.map(paragraph) }, storylineId, ordinal: sceneIndex, createdAt: now, updatedAt: now });
const linkedNoteIds = seedScene.notes.map((title) => { const noteId = noteIds.get(title); if (!noteId) { throw new Error(`Scene "${seedScene.title}" links unknown note "${title}".`); } return noteId; });
for (const noteId of linkedNoteIds) { tx.insert(tables.sceneNote).values({ sceneId, noteId }).run(); }
/* * A scene on a storyline needs a card, or the example's grid is empty rows * that read as an unfinished feature rather than a place to plan. */ if (storylineId) { const cardId = crypto.randomUUID(); tx.insert(tables.plotCard) .values({ id: cardId, storylineId, sceneId, title: seedScene.title, body: seedScene.card || seedScene.paragraphs[0] || '', ordinal: sceneIndex, createdAt: now, updatedAt: now }) .run();
for (const noteId of linkedNoteIds) { tx.insert(tables.plotCardNote).values({ cardId, noteId }).run(); } } }}
function inlineNodes(line: string) { return line .split(/(\*\*[^*]+\*\*|\*[^*]+\*)/g) .filter(Boolean) .map((part) => { if (part.startsWith('**') && part.endsWith('**') && part.length > 4) { return { type: 'text', text: part.slice(2, -2), marks: [{ type: 'bold' }] }; } if (part.startsWith('*') && part.endsWith('*') && part.length > 2) { return { type: 'text', text: part.slice(1, -1), marks: [{ type: 'italic' }] }; } return { type: 'text', text: part }; });}
/** * One paragraph of the example prose. A line break inside it becomes a hard * break, which is how the one verse in the book keeps its lines. */function paragraph(text: string) { return { type: 'paragraph', content: text .split('\n') .flatMap((line, index) => index === 0 ? inlineNodes(line) : [{ type: 'hardBreak' }, ...inlineNodes(line)] ) };}
/** * A small Markdown subset for seed note bodies: `##` prompt headings from the * note templates, `*italic*` and `**bold**` inline marks, and blank-line * paragraphs. */function markdownToDoc(text: string) { return text.split('\n\n').map((block) => { if (block.startsWith('## ')) { return { type: 'heading', attrs: { level: 2 }, content: inlineNodes(block.slice(3).trim()) }; }
return paragraph(block); });}