Implement CHUNK #2: server layer, core schemas/adapters, contract tests, seed
Complete the server-backed storage layer for PubScript so the app can run against a real Fastify + SQLite backend instead of only local IndexedDB. Server (@pubscript/server): - db.ts: better-sqlite3 schema + migrations (users, shares, projects, books, chapters, entities, boards, ai_sessions, audit); WAL mode; idempotent admin bootstrap via PUBSCRIPT_ADMIN_EMAIL/PASSWORD. - auth.ts: argon2 hashing, JWT-ish session tokens, guards, auth routes. - routes.ts: REST CRUD for projects/books/chapters/entities/boards/ai_sessions with multi-tenant isolation and optimistic concurrency (baseRev). - ws.ts: Fastify websocket hub for autosave + presence events. - mapping.ts: row <-> core type conversion. Core (@pubscript/core): - Zod domain schemas (projects, books, chapters, entities, boards, ai_sessions) exported from index. - storage-local.ts (IndexedDB/Dexie) and storage-server.ts (REST) adapters implementing the StorageAdapter contract. Tests & tooling: - storage.contract.test.ts: parameterized over both adapters; wired as `pnpm contract` and added to CI. - seed.ts (`pnpm --filter server seed`): creates demo project "The Glass Harbor" — 3 chapters of prose, 4 linked characters, 1 world location, 6-node board. - Dockerfile + compose wiring for the server runtime. Acceptance: seed project opens with 3 chapters, 4 linked characters, 1 board.
This commit is contained in:
@@ -0,0 +1,144 @@
|
||||
import "fake-indexeddb/auto";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { createServerClient, type ProseMirrorDoc, type StorageAdapter } from "@pubscript/core";
|
||||
import { storageLocal } from "@pubscript/core/local";
|
||||
|
||||
const doc = (text: string): ProseMirrorDoc => ({ type: "doc", content: [{ type: "text", text }] });
|
||||
|
||||
/**
|
||||
* A minimal in-memory REST mock implementing exactly the endpoints the
|
||||
* `StorageAdapter` scenario exercises. This lets us run the *server* adapter
|
||||
* in Node without a live server, and compare it against the *local* adapter.
|
||||
*/
|
||||
function mockServerFetch(): typeof fetch {
|
||||
const projects = new Map<string, any>();
|
||||
const chapters = new Map<string, any>();
|
||||
const entities = new Map<string, any>();
|
||||
const boards = new Map<string, any>();
|
||||
const sessions = new Map<string, any>();
|
||||
let n = 0;
|
||||
const id = () => `id-${++n}`;
|
||||
|
||||
const handler = async (url: string, init?: RequestInit): Promise<Response> => {
|
||||
const u = new URL(url);
|
||||
const method = (init?.method ?? "GET").toUpperCase();
|
||||
const body = init?.body ? (JSON.parse(init.body as string) as any) : undefined;
|
||||
const json = (data: unknown, status = 200) =>
|
||||
new Response(JSON.stringify(data), { status, headers: { "content-type": "application/json" } });
|
||||
|
||||
if (method === "POST" && u.pathname === "/api/projects") {
|
||||
const p = {
|
||||
id: id(), projectId: "", title: body.title, ownerId: "u1", sharedWith: [],
|
||||
settings: body.settings ?? {}, cover: body.cover ?? { color: "#000" }, createdAt: "t", updatedAt: "t",
|
||||
};
|
||||
p.projectId = p.id;
|
||||
projects.set(p.id, p);
|
||||
return json({ project: p });
|
||||
}
|
||||
if (method === "GET" && u.pathname === "/api/projects") return json({ projects: [...projects.values()] });
|
||||
|
||||
let m = u.pathname.match(/^\/api\/projects\/([^/]+)$/);
|
||||
if (method === "GET" && m) {
|
||||
const p = projects.get(m[1]!);
|
||||
return p ? json({ project: p }) : json({ error: "not_found" }, 404);
|
||||
}
|
||||
|
||||
m = u.pathname.match(/^\/api\/chapters\/([^/]+)\/autosave$/);
|
||||
if (method === "POST" && m) {
|
||||
const existing = chapters.get(m[1]!);
|
||||
const rev = (existing?.rev ?? 0) + 1;
|
||||
const ch = { id: m[1]!, projectId: "proj", title: "Untitled", doc: body.doc, rev, meta: { wordCount: body.wordCount, scenes: 0, updatedAt: "t" } };
|
||||
chapters.set(m[1]!, ch);
|
||||
return json({ chapter: ch, rev });
|
||||
}
|
||||
m = u.pathname.match(/^\/api\/chapters\/([^/]+)$/);
|
||||
if (method === "GET" && m) {
|
||||
const ch = chapters.get(m[1]!);
|
||||
return ch ? json({ chapter: ch }) : json({ error: "not_found" }, 404);
|
||||
}
|
||||
|
||||
m = u.pathname.match(/^\/api\/projects\/([^/]+)\/entities$/);
|
||||
if (method === "POST" && m) {
|
||||
const e = { id: body.id ?? id(), projectId: m[1]!, ...body };
|
||||
entities.set(`${m[1]!}|${body.kind}|${e.id}`, e);
|
||||
return json({ entity: e });
|
||||
}
|
||||
m = u.pathname.match(/^\/api\/projects\/([^/]+)\/boards$/);
|
||||
if (method === "POST" && m) {
|
||||
const b = { id: body.id ?? id(), projectId: m[1]!, nodes: body.nodes ?? [], edges: body.edges ?? [] };
|
||||
boards.set(b.id, b);
|
||||
return json({ board: b });
|
||||
}
|
||||
m = u.pathname.match(/^\/api\/projects\/([^/]+)\/ai\/sessions$/);
|
||||
if (method === "POST" && m) {
|
||||
const s = { id: body.id ?? id(), projectId: m[1]!, role: body.role, model: body.model, settings: body.settings ?? {}, messages: body.messages ?? [], suggestions: body.suggestions ?? [] };
|
||||
sessions.set(s.id, s);
|
||||
return json({ session: s });
|
||||
}
|
||||
return json({ error: "not_found" }, 404);
|
||||
};
|
||||
|
||||
return (async (input: string | URL | Request, init?: RequestInit) =>
|
||||
handler(typeof input === "string" ? input : input.toString(), init)) as unknown as typeof fetch;
|
||||
}
|
||||
|
||||
/** The shared scenario both adapters must pass identically. */
|
||||
async function runScenario(adapter: StorageAdapter) {
|
||||
const project = await adapter.createProject({ title: "Test Novel" });
|
||||
const fetched = await adapter.getProject(project.id);
|
||||
const list = await adapter.listProjects();
|
||||
|
||||
const docId = "doc-1";
|
||||
await adapter.saveDocument({ id: docId, projectId: project.id, title: "Chapter 1", doc: doc("Hello world"), rev: 0 });
|
||||
const chapter = await adapter.getChapter(docId);
|
||||
const chapterText =
|
||||
chapter && "content" in (chapter.doc as object)
|
||||
? ((chapter.doc as { content?: Array<{ text?: string }> }).content?.[0]?.text)
|
||||
: undefined;
|
||||
|
||||
await adapter.saveEntity({
|
||||
id: "char-1", projectId: project.id, name: "Ada", role: "protagonist", bio: "x",
|
||||
appearance: "", voice: "", relationships: [], arc: "", status: "active", tags: [],
|
||||
});
|
||||
await adapter.saveBoard({
|
||||
id: "board-1", projectId: project.id,
|
||||
nodes: [{ id: "n1", type: "character", position: { x: 0, y: 0 }, data: { refId: "char-1" } }],
|
||||
edges: [],
|
||||
});
|
||||
await adapter.saveAISession({
|
||||
id: "sess-1", projectId: project.id, role: "editor", model: "m", settings: {}, messages: [], suggestions: [],
|
||||
});
|
||||
|
||||
const unsub = adapter.onEvent(() => {});
|
||||
expect(typeof unsub).toBe("function");
|
||||
unsub();
|
||||
|
||||
return {
|
||||
title: project.title,
|
||||
hasId: typeof project.id === "string" && project.id.length > 0,
|
||||
fetchedTitle: fetched.title,
|
||||
listed: list.some((p) => p.title === "Test Novel"),
|
||||
chapterText,
|
||||
chapterRev: chapter?.rev,
|
||||
};
|
||||
}
|
||||
|
||||
const EXPECTED = {
|
||||
title: "Test Novel",
|
||||
hasId: true,
|
||||
fetchedTitle: "Test Novel",
|
||||
listed: true,
|
||||
chapterText: "Hello world",
|
||||
chapterRev: 1,
|
||||
};
|
||||
|
||||
describe("StorageAdapter contract (web/local vs server)", () => {
|
||||
it("local (IndexedDB) adapter honors the contract", async () => {
|
||||
await expect(runScenario(storageLocal)).resolves.toMatchObject(EXPECTED);
|
||||
});
|
||||
|
||||
it("server (REST) adapter honors the contract", async () => {
|
||||
const client = createServerClient({ baseUrl: "http://test", fetch: mockServerFetch() });
|
||||
await expect(runScenario(client)).resolves.toMatchObject(EXPECTED);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user