/** * A save names the revision it was built on. The server writes only at that * revision; otherwise it answers 409 with the current words, so the browser can * show the writer both versions. */ /** What a save names to prove it knows the current words. */ export type SavePrecondition = { /** The revision the browser last saw. */ baseRevision: number; /** * The writer chose to put their version over a newer one. The server still * checks `baseRevision`, so it can only replace the version the writer saw. */ replace?: boolean; }; /** A document's words as the server holds them. */ export type DocumentVersion = { revision: number; body: unknown; text: string; words: number; savedAt: Date; }; export type SaveOutcome = | { ok: true; revision: number } | { ok: false; reason: 'gone' } | { ok: false; reason: 'conflict'; current: DocumentVersion }; /** Null when the precondition is missing or malformed. */ export function readPrecondition(payload: unknown): SavePrecondition | null { if (!payload || typeof payload !== 'object' || Array.isArray(payload)) return null; const { baseRevision, replace } = payload as { baseRevision?: unknown; replace?: unknown }; if (typeof baseRevision !== 'number' || !Number.isInteger(baseRevision)) return null; return { baseRevision, replace: replace === true }; } export function failure(status: number, message: string): Response { return Response.json({ message }, { status }); } /** * Carries the server's words so the editor can offer them without a second * request, and `code` so a client need not infer a conflict from the status. */ export function conflictResponse(current: DocumentVersion): Response { return Response.json( { code: 'conflict', message: 'This was saved somewhere else since you opened it.', revision: current.revision, body: current.body, text: current.text, words: current.words, savedAt: current.savedAt.toISOString() }, { status: 409 } ); }