import { g as CollectionConfig } from "./rule-DYNYH_ha.js"; import { O as ResolveEditor, n as WorkerRoute } from "./index-FUN1hqS9.js"; import { i as EditorSession } from "./types-B8yzm4Q0.js"; import { O as DeferReindex, at as PageId, ot as VersionId } from "./index-BtXZuYn4.js"; import { _ as pageRedirects } from "./index-ByWtUw-d.js"; import { SQLiteTable } from "drizzle-orm/sqlite-core"; //#region src/core/editor/shared.d.ts /** The minimum a Worker `env` must expose for the editor routes: the D1 binding. * Media routes widen this with the R2 bindings (see LouiseMediaEnv). */ interface EditorRouteEnv { DB: D1Database; } /** JSON response with a status + optional extra headers (thin wrapper over * `Response.json`). */ declare function json(data: unknown, status?: number, headers?: HeadersInit): Response; /** True when the request's pathname is exactly `path`. */ declare function matchPath(request: Request, path: string): boolean; /** * Resolve the editor session and run the shared same-origin + session guard * ({@link requireEditor}). Returns the editor on success, or a `Response` to * short-circuit the route. `mutation` gates the same-origin (CSRF) check—`false` * for reads, `true` for writes. */ declare function guardEditor(request: Request, env: Env, resolveEditor: ResolveEditor, mutation: boolean): Promise<{ editor: EditorSession; } | { response: Response; }>; /** * Validate + double-quote a SQL identifier (table/column). Identifiers come * from a site's own Drizzle schema, never user input, but quote them anyway as * defense in depth so a typo can't become injection (mirrors louise-toolkit/media's * `findMediaReferences`). */ declare function ident(name: string): string; /** The SQL table name + primary-key column name for a Drizzle SQLite table. */ declare function tableMeta(table: SQLiteTable): { name: string; pk: string; }; /** * Run an editor {@link WorkerRoute} from a non-Worker context—a framework * `APIRoute`, a Nitro/Nuxt handler, etc.—where you already have the resolved * editor session (for example, from middleware) and the bindings, but no * `ExecutionContext`. Supplies a no-op `ctx` and turns a path fall-through * (`undefined`) into a 404, so a consuming route is a one-liner: * * ```ts * // The session is already resolved by the host; hand it back via resolveEditor. * export const ALL: APIRoute = (ctx) => * runEditorRoute( * inquiriesRoute({ table: inquiries, resolveEditor: () => ctx.locals.editor }), * ctx.request, * env, * ); * ``` */ declare function runEditorRoute(route: WorkerRoute, request: Request, env: Env): Promise; //#endregion //#region src/core/editor/draft-buffer.d.ts /** The KV surface the buffer needs—structural so the real `KVNamespace` fits * without a hard dependency. Unlike `security`'s `KVLike`, this also needs * `delete` (to clear a buffer on publish). */ interface DraftBufferKV { get(key: string): Promise; put(key: string, value: string, options?: { expirationTtl?: number; }): Promise; delete(key: string): Promise; } /** A page's buffered working draft. `data` is the full field snapshot (the same * shape a version's `versionData` holds). */ interface BufferedDraft { data: Record; /** Last buffer write (ms epoch). */ updatedAt: number; /** Last flush to D1 (ms epoch); `0` when never flushed. */ flushedAt: number; } /** Default self-expiry for an abandoned buffer: 7 days. */ declare const DRAFT_BUFFER_TTL_SECONDS: number; /** Default flush cadence: coalesce D1 writes to at most one per 10 seconds while a burst * of edits continues. */ declare const DEFAULT_FLUSH_MS = 10000; /** KV key for a collection row's draft buffer. The `v2` segment marks buffers * written after a buffered save began running the collection's `beforeChange` * hooks. Earlier buffers could hold unsanitized input, so they're never read; * they expire on their own TTL. */ declare function draftBufferKey(collection: string, id: number | string): string; /** Read + parse a page's buffer, or `null` when absent/corrupt. */ declare function readDraftBuffer(kv: DraftBufferKV, key: string): Promise; /** Write a page's buffer with a self-expiry TTL. */ declare function writeDraftBuffer(kv: DraftBufferKV, key: string, draft: BufferedDraft, ttlSeconds?: number): Promise; /** Delete a page's buffer (on publish, or when discarding pending work). */ declare function clearDraftBuffer(kv: DraftBufferKV, key: string): Promise; /** * Should this auto-save flush to D1, or just update the buffer? Flush when there * is no buffer yet (establish the D1 draft row so `hasDraft` + resume work even * if the buffer later expires) or when at least `flushMs` has elapsed since the * last flush. Otherwise the write is absorbed by the buffer alone. */ declare function shouldFlushBuffer(buffer: BufferedDraft | null, now: number, flushMs: number): boolean; //#endregion //#region src/core/editor/revs.d.ts /** The body key a draft save carries its base revisions under, beside the fields. */ declare const DRAFT_BASE_KEY = "$base"; /** One field a draft save couldn't apply, because someone else changed it. */ interface DraftConflict { /** The field key. */ field: string; /** The value stored now, which the save would have overwritten. */ value: unknown; /** Its revision, to send as the base when the owner keeps their own edit. */ rev: string; } /** * A field value's revision: the first 16 hex characters of the SHA-256 of its * JSON. `undefined` hashes as `null`. Stable across a store and a read, because * a JSON round trip keeps key order. */ declare function fieldRev(value: unknown): Promise; /** The revisions of `keys` in `data`, as a field → revision map. */ declare function fieldRevs(data: Record, keys: Iterable): Promise>; /** `value` as a field → revision map, or `undefined` when it isn't one. */ declare function parseDraftBase(value: unknown): Record | undefined; //#endregion //#region src/core/editor/versions.d.ts /** The store-side deps a versioned draft save needs—the subset of * {@link VersionsRouteConfig} that {@link applySaveDraft} uses (no transport/auth * concern), shared with the host's `saveDraft` endpoint so the raw route and the * Action build the same versioned local API and buffer. */ interface SaveDraftDeps { /** The main content table (for example, the composed `pages`). */ table: SQLiteTable; /** The `${slug}_versions` companion table (see content codegen's `collectionVersionsTable`). */ versionsTable: SQLiteTable; /** The collection config—its `fields` drive the draft snapshot + publish validation. */ config: CollectionConfig; /** * Optional validation of the full merged draft before it's saved (for example, the * site's `assertValidSections`). Throw to reject the draft with the thrown * error's message; a `LouiseValidationError` surfaces its `violations`. */ validate?: (data: Record) => void | Promise; /** * Move FTS reindex off the publish path (#77). Given the runtime `env` (so it * can reach a queue binding), return a {@link DeferReindex} that enqueues a * reindex of the published row's id instead of syncing the index inline; the * consumer drains it with `reindexDoc`. Return `undefined` (or omit) to keep * syncing inline—so a site without a queue keeps working unchanged. */ deferReindex?: (env: Env) => DeferReindex | undefined; /** * Coalesce high-frequency auto-save writes through a KV buffer (#70). Given * the runtime `env`, return the KV namespace to buffer working drafts in; * return `undefined` (or omit) to write every draft straight to D1 (unchanged). * When set: each auto-save updates the buffer, and D1 is flushed only on the * first write, every {@link bufferFlushMs}, and on publish (which then clears * the buffer). Resume reads should prefer the buffer—see `readDraftBuffer`. */ bufferKv?: (env: Env) => DraftBufferKV | undefined; /** Flush cadence for the KV buffer, ms. Default {@link DEFAULT_FLUSH_MS} (10 seconds). */ bufferFlushMs?: number; } interface VersionsRouteConfig extends SaveDraftDeps { /** Resolve the editor session (site wraps its own auth). */ resolveEditor: ResolveEditor; /** Mount path (the collection base). Default `/api/louise/pages`. */ path?: string; /** * The soft-locks a draft save respects (#572), from the site's realtime * session: `realtimeSoftLocks` from `louise-toolkit/realtime`. See * {@link SaveDraftOptions.softLocks}. */ softLocks?: DraftSoftLocks; /** * Remember a page's old URL when a publish changes its slug (#574): the * `pageRedirects` table from `louise-toolkit/db`, as `pagesRoute` takes it. * The publish runs its own write, so the redirect is written right after it; * if that fails, the publish still stands and the failure is reported as * `editor.redirects`. */ redirects?: typeof pageRedirects; } /** The page a soft-lock read is for. */ interface DraftSoftLockTarget { /** The collection slug. */ slug: string; /** The row being saved. */ id: PageId; } /** * Where a draft save finds the soft-locks another editor holds (#572). A * realtime session only enforces its locks on its own socket, so a save that * reaches the draft route another way (a surface whose socket dropped, a * second tab without one, a script) checks them here. */ interface DraftSoftLocks { /** The fields under a soft-lock: the session's `lockFields`. A save that * changes none of them never reads the locks. */ fields: readonly string[]; /** The held locks on a row, as field name → the holder's user ID. Throw when * they can't be read, and the save goes ahead unchecked and reports it. */ read: (env: Env, target: DraftSoftLockTarget) => Promise>>; } /** The outcome of {@link applySaveDraft}: on success the exact JSON body + status * the raw route returns (a created `version` at 201, or `{ buffered: true }` at * 200 when a KV write is coalesced), plus the D1 session `bookmark` to persist * for read-your-writes on resume (#69)—`undefined` on a non-replicated D1 / * runtime without the Sessions API; on failure a status + message (+ optional * per-field `violations` from a `validate` throw). */ type SaveDraftResult = { ok: true; status: number; body: Record; bookmark?: string; } | { ok: false; status: number; error: string; violations?: unknown; /** On a 409: the fields someone else changed since `base`. */ conflicts?: DraftConflict[]; /** On a 423: the fields this save changes that another editor holds. */ locked?: string[]; }; /** Options for {@link applySaveDraft}. */ interface SaveDraftOptions { /** * The field revisions the save started from, from the `revs` of an earlier * save or of `GET /:id/versions`. A field in the save whose stored value * has moved since its revision here is a conflict, and the save answers 409 * with the current values instead of merging, unless the new value already * equals the stored one. A field with no revision here isn't checked, so a * save without `base` merges as it always has. * * With the KV buffer on, the check reads the buffer and then writes it, and * KV isn't atomic, so two saves that land together can both pass. The check * narrows that window; it doesn't close it. */ base?: Record; /** * The soft-locks this save respects (#572). A save that changes a field * another editor holds answers 423 with `locked`, and nothing is written. A * field whose new value equals the stored one isn't a change, and the lock * holder's own save goes through. When the locks can't be read, the save * goes ahead and the failure is reported as `editor.softLocks`. * * The realtime session's own `persist` leaves this out: the session already * enforces its locks, and its coalesced flush can carry a locked field * another editor wrote. */ softLocks?: DraftSoftLocks; /** * The surface the save came through, recorded on the version when the * collection sets `versions.provenance`. The realtime session's `persist` * passes `"realtime"`. Leave it out for an editor route. An agent's save is * recorded as `"agent"` from its session whatever this says. */ source?: "realtime"; } /** * Save an already-validated draft for a versioned row: merge the edit (config * fields only) over the freshest pending work—the KV buffer, else the newest * pending draft's snapshot, else the live row (see {@link latestPendingDraft})—optionally * run the site's `validate`, then either absorb the write into the KV * buffer (#70) or write a new draft version to D1. Carries no transport/parse * concern—the raw {@link versionsRoute} (POST `/:id/versions`) and the host's * `saveDraft` Action each validate their own input, then converge here. */ declare function applySaveDraft(env: Env, deps: SaveDraftDeps, editor: EditorSession, id: PageId, input: Record, options?: SaveDraftOptions): Promise; /** The outcome of {@link applyPublish}: the live row, or a status and message * (with per-field `violations` when a hook or validation refused it). */ type PublishResult = { ok: true; body: { page: unknown; }; } | { ok: false; status: number; error: string; violations?: unknown; }; /** What {@link applyPublish} needs: the draft deps, plus the redirects table. */ interface PublishDeps extends SaveDraftDeps { /** See {@link VersionsRouteConfig.redirects}. */ redirects?: typeof pageRedirects; } /** * Publish a versioned row, as `POST /:id/publish` does. With `versionId`, that * version, which must belong to `id`. Without it, the newest still-pending * draft, after flushing any buffered work into one. With no pending draft, a * hidden row is shown again as it stands, and a row never published goes live * as it stands. Otherwise there's nothing to publish. * * The collection's `publish` access function decides whether `editor` may, so * the MCP route's `publish_` and the editor's own button share one rule. */ declare function applyPublish(env: Env, deps: PublishDeps, editor: EditorSession, id: PageId, explicitVersionId?: VersionId): Promise; /** * The newest still-*pending* draft among `versions` (which {@link findVersions} * returns newest-first, so the first match is the newest), or `undefined` when * there is none. A draft is pending only if it's newer than every version ever * promoted (ADR 0021's high-water mark); a draft at or below it is * *superseded*—publishing has already moved past it, so it must not be resumed * or auto-published as if it were current work. The mark, not the live pointer, * because the pointer moves back when an older version is republished, and * that mustn't bring stale drafts back. * * This backs two behaviours: * - **Concurrent surfaces (draft merge base):** a versioned page may mount more * than one editing surface (for example, a rich-text body canvas and a sections dock), * each saving only the fields it owns. Layering every partial save over the * newest pending draft—instead of always over the live row—lets those * surfaces compose into one snapshot rather than each reverting the other's * pending work. * - **Publish with no explicit `versionId`:** promoting "the latest draft" must * skip superseded drafts so a stale snapshot can't silently go live. */ declare function latestPendingDraft(versions: readonly Record[]): Record | undefined; /** * Build the draft/publish/versions route for a versioned collection. Returns * `undefined` for any path it doesn't own so `composeWorker` falls through. */ declare function versionsRoute(cfg: VersionsRouteConfig): WorkerRoute; //#endregion export { json as A, draftBufferKey as C, EditorRouteEnv as D, writeDraftBuffer as E, runEditorRoute as M, tableMeta as N, guardEditor as O, clearDraftBuffer as S, shouldFlushBuffer as T, parseDraftBase as _, SaveDraftDeps as a, DRAFT_BUFFER_TTL_SECONDS as b, VersionsRouteConfig as c, latestPendingDraft as d, versionsRoute as f, fieldRevs as g, fieldRev as h, PublishResult as i, matchPath as j, ident as k, applyPublish as l, DraftConflict as m, DraftSoftLocks as n, SaveDraftOptions as o, DRAFT_BASE_KEY as p, PublishDeps as r, SaveDraftResult as s, DraftSoftLockTarget as t, applySaveDraft as u, BufferedDraft as v, readDraftBuffer as w, DraftBufferKV as x, DEFAULT_FLUSH_MS as y };