import type { EponymeAction, EponymeCollectionDefinitionBase, EponymeConfig, EponymeSchema, EponymeStatus } from '../../types/index.js'; import { type ValidationErrors } from '../../utils/validate-eponyme-data.js'; import { type EponymeIndexRow } from '../../utils/eponyme-entry-index.js'; import { type EponymeSharedCacheStorage } from './eponyme-cache-store.js'; import type { EponymeCacheFailureContext } from '../../types/hooks.js'; import type { EponymePermissionAction } from '../../types/permissions.js'; import type { EponymeReferrer, EponymeRelationTarget } from '../../types/relations.js'; import { type EponymePopulateResult } from '../../utils/eponyme-populate.js'; export type { EponymeAction, EponymeStatus } from '../../types/index.js'; export type EponymeVersion = 'draft' | 'published'; /** Either the live draft/published content, or a numeric id from the version history. */ export type EponymeVersionSelector = EponymeVersion | number; export interface EponymeSchedule { scheduledPublishAt?: string | null; scheduledUnpublishAt?: string | null; } export interface EponymeResult { data: Record; status: EponymeStatus; publishedAt: string | null; scheduledPublishAt: string | null; scheduledUnpublishAt: string | null; /** The optimistic lock token, sent back with the next write of this entry. */ revision: string | null; /** When the row was last written. Absent on a version read from the history. */ updatedAt?: string | null; } export interface EponymeVersionAuthor { id: string; username: string; } export type EponymeActor = EponymeVersionAuthor; export interface EponymeHistoryEntry { id: number; action: EponymeAction | 'restore' | 'import'; status: EponymeStatus; createdAt: string; user: EponymeVersionAuthor | null; } /** Raised when a concurrent write changed the entry between our read and our write. */ export interface EponymeConflict { conflict: true; errors?: never; } /** Raised when the actor may restore, but not the change to the public site the restore would make. */ export interface EponymeForbidden { forbidden: EponymePermissionAction; errors?: never; } /** How a route says what the actor is allowed to do, without the store knowing about roles. */ export interface EponymeRestoreOptions { allows?: (action: EponymePermissionAction) => boolean; } export interface EponymeScheduleTransition extends EponymeResult { name: string; action: 'publish' | 'unpublish'; } export interface EponymeCollectionEntry = Record> { slug: string; title: string; data: Data; status: EponymeStatus; publishedAt: string | null; scheduledPublishAt: string | null; scheduledUnpublishAt: string | null; updatedAt: string | null; /** Only set for entries read from the trash. */ deletedAt?: string | null; } export interface EponymeSitemapEntry { loc: string; lastmod?: string; } /** One entry of an export file: the complete stored state, without the envelope. */ export interface EponymeExportEntry { name: string; /** Set for collection entries, so a reader can group them without re-parsing the name. */ collection?: string; draft: Record; published: Record; status: EponymeStatus; publishedAt: string | null; scheduledPublishAt: string | null; scheduledUnpublishAt: string | null; } export interface EponymeExportFile { eponyme: { format: 1; exportedAt: string; /** Schema fingerprint per singleton and per collection, checked before an import writes anything. */ schemas: Record; }; entries: EponymeExportEntry[]; } export interface EponymeImportResult { dryRun: boolean; created: number; updated: number; skipped: Array<{ name: string; reason: string; }>; } /** An entry the import actually wrote, as the hooks the route emits need to describe it. */ export interface EponymeImportedEntry extends EponymeResult { name: string; collection?: { name: string; slug: string; }; /** Whether the entry was published before the import, so the route can emit an unpublication. */ wasPublished: boolean; } export interface EponymeImportOutcome extends EponymeImportResult { written: EponymeImportedEntry[]; } /** The import was refused as a whole, before any write. */ export interface EponymeImportRejection { errors: string[]; /** Names whose configured schema differs from the one the file was exported with. */ schemaMismatch?: string[]; } export type EponymeSortDirection = 'asc' | 'desc'; /** Comparisons a filter may ask for. Only fields stored in a sortable text form accept one. */ export interface EponymeFilterRange { gte?: string; lte?: string; gt?: string; lt?: string; } export interface EponymeFilterOperators extends EponymeFilterRange { in?: string[]; /** Excluded values. Resolved by subtraction: the index only records what is there. */ not?: string[]; contains?: string; } /** One condition of a `where`. */ export type EponymeFilterCondition = string | string[] | EponymeFilterOperators; export interface EponymeCollectionQuery { take?: number; skip?: number; orderBy?: string; order?: EponymeSortDirection; /** Keyed by field name. Only the keys `collectionFilterKeys` reports can be used. */ where?: Record; /** Substring of the title or of the slug. */ search?: string; } export interface EponymeCollectionPage = Record> { entries: EponymeCollectionEntry[]; /** Matching entries before `take` and `skip`, so it can drive a pager. */ total: number; } /** What a listing returns with `fields=meta`: the entry without its payload. */ export type EponymeCollectionEntryMeta = Omit; export declare const COLLECTION_METADATA_KEYS: readonly ["updatedAt", "publishedAt", "title", "slug"]; export type PrismaEponymeRow = { name: string; draft?: unknown; published?: unknown; status?: string; publishedAt?: Date | string | null; scheduledPublishAt?: Date | string | null; scheduledUnpublishAt?: Date | string | null; updatedAt?: Date | string; deletedAt?: Date | string | null; }; export type EponymeRowWrite = { draft: Record; published: Record; status: EponymeStatus; publishedAt: Date | null; scheduledPublishAt: Date | null; scheduledUnpublishAt: Date | null; }; export type PrismaEponymeSelect = { name?: true; draft?: true; published?: true; status?: true; publishedAt?: true; scheduledPublishAt?: true; scheduledUnpublishAt?: true; updatedAt?: true; }; export type PrismaEponymeWhere = { /** `in` is what a filtered listing uses: the index resolves the names first. */ name?: string | { startsWith: string; } | { in: string[]; }; deletedAt?: PrismaDeletedAtFilter; publishedAt?: { not: null; }; status?: EponymeStatus; scheduledPublishAt?: null | { lte: Date; }; scheduledUnpublishAt?: null | { gt: Date; } | { lte: Date; }; AND?: PrismaEponymeWhere[]; OR?: PrismaEponymeWhere[]; }; export type PrismaEponymeQuery = { where: PrismaEponymeWhere; orderBy?: PrismaEponymeOrderBy[]; take?: number; skip?: number; }; /** * `nulls` appears on `publishedAt` alone: Prisma refuses it on a column that cannot be null, and * `updatedAt` never is. */ export type PrismaEponymeOrderBy = { name: 'asc'; } | { updatedAt: EponymeSortDirection; } | { publishedAt: { sort: EponymeSortDirection; nulls: 'last'; }; }; /** `null` keeps the live rows, `{ not: null }` the trashed ones. */ export type PrismaDeletedAtFilter = null | { not: null; }; export type PrismaEponymeVersionRow = { id: number; entryName: string; data: unknown; action: string; status: string; createdAt: Date | string; userId?: string | null; user?: { id: string; username: string; } | null; }; /** The model delegates, which a transaction exposes just like the client does. */ export type PrismaEponymeDelegates = { eponyme: { upsert(args: { where: { name: string; }; create: EponymeRowWrite & { name: string; }; update: Partial; }): Promise; update(args: { where: { name: string; }; data: EponymeRowWrite; }): Promise; /** Used as a compare-and-swap: the `updatedAt` guard makes concurrent writes fail instead of overwriting. */ updateMany(args: { where: { name: string; updatedAt?: Date | string; deletedAt?: PrismaDeletedAtFilter; }; data: Partial & { deletedAt?: Date | null; }; }): Promise<{ count: number; }>; create(args: { data: EponymeRowWrite & { name: string; }; }): Promise; findUnique(args: { where: { name: string; }; }): Promise; /** * One signature rather than an overload per `select`: every column of `PrismaEponymeRow` but `name` is * optional, so a narrowed row satisfies it as it is. */ findMany(args: PrismaEponymeQuery & { select?: PrismaEponymeSelect; }): Promise; count(args: PrismaEponymeQuery): Promise; delete(args: { where: { name: string; }; }): Promise; }; eponymeVersion: { create(args: { data: { entryName: string; data: Record; action: string; status: EponymeStatus; userId?: string | null; }; }): Promise; findMany(args: { where: { entryName: string; }; orderBy: { createdAt: 'desc'; }; take: number; include?: { user: true; }; }): Promise; findUnique(args: { where: { id: number; }; }): Promise; }; eponymeEntryIndex: { /** The rows of an entry are replaced as a whole, so a removed value cannot survive. */ deleteMany(args: { where: { entryName: string | { startsWith: string; }; }; }): Promise<{ count: number; }>; createMany(args: { data: EponymeIndexRow[]; }): Promise<{ count: number; }>; findMany(args: { where: { /** Absent when the question is "who points at this", which spans every collection. */ entryName?: { startsWith: string; }; version?: 'draft' | 'published'; key: string; value: PrismaStringFilter; }; select: { entryName: true; }; }): Promise>; }; eponymeIndexState: { findMany(): Promise>; upsert(args: { where: { name: string; }; create: { name: string; fingerprint: string; }; update: { fingerprint: string; }; }): Promise<{ name: string; fingerprint: string; }>; deleteMany(args: { where: { name: { in: string[]; }; }; }): Promise<{ count: number; }>; }; eponymeAuditEvent: { create(args: { data: Record; }): Promise; }; }; export type PrismaStringFilter = string | { in?: string[]; /** Substring match. A leading wildcard cannot use the index's ordering, so this scans. */ contains?: string; gte?: string; lte?: string; gt?: string; lt?: string; }; export type PrismaEponymeClient = PrismaEponymeDelegates & { $transaction(fn: (tx: PrismaEponymeDelegates) => Promise, options?: { maxWait?: number; timeout?: number; }): Promise; }; interface StoredEponymeState { __eponyme: { version: 1; draft: Record; published: Record; status: EponymeStatus; publishedAt: string | null; scheduledPublishAt: string | null; scheduledUnpublishAt: string | null; }; } export declare class EponymeService { private readonly client; private readonly schemas; private readonly collections; /** Entries a read has already persisted the normalized shape for, so it only attempts it once. */ private readonly healedByRead; /** `\n` a heal superseded, mapped to the revision it wrote in its place. */ private readonly healedRevisions; /** * Read-path cache of normalized rows, so a page that reads the same entry from a singleton, a listing and * a layout pays one round trip instead of one per read. */ private readonly cache; constructor(config: EponymeConfig, client: PrismaEponymeClient, options?: { cacheSeconds?: number; cacheStorage?: string; resolveCacheStorage?: (mount: string) => EponymeSharedCacheStorage; onCacheFailure?: (context: EponymeCacheFailureContext) => void; }); private cached; /** * Drops what a write to `name` invalidates: the entry itself, and the listing of the collection that * contains it, whose row set just changed. */ private invalidate; /** Replaces an entry's filterable values, in the same transaction as the write that changed them. */ private reindexEntry; private audit; collectionFilterKeys(name: string): string[] | undefined; /** * One transaction per entry rather than one for the whole collection: a collection has no bound, and a * single transaction over it would exceed Prisma's timeout on anything real. */ private reindexName; private indexedNames; /** The unconditional rebuild, for a first backfill or a manual repair. */ reindexAll(): Promise<{ entries: number; }>; /** Rebuilds only what a configuration change invalidated, and nothing when nothing changed. */ syncIndexState(): Promise<{ reindexed: string[]; }>; private indexFingerprint; private writeIndexState; /** Runs writes that have to land together, then drops what they invalidated. */ private transaction; getSchema(name: string): EponymeSchema | undefined; isSingleton(name: string): boolean; getCollection(name: string): EponymeCollectionDefinitionBase | undefined; private getCollectionEntry; /** Reconcile every configured eponyme at application startup. This is the one place that heals. */ /** Reconcile and normalise every stored row at startup, including trashed collection entries. */ syncAll(): Promise; /** * Brings a stored document back in line with the schema: keys the schema no longer declares are dropped, * and a key it declares but the document lacks takes its default. */ private reconcile; /** Descends into the containers; a leaf is returned untouched for `reconcile` to judge. */ private reconcileField; private createState; /** Reads a state out of an envelope. */ private normalizeState; private rowToState; /** A singleton row is created on first read, but only when it is genuinely missing. */ private loadSingletonRow; /** Reads the stored state along with the `updatedAt` it was read at, used as the optimistic lock token. */ private loadRow; private readRow; private loadState; /** Persists the normalized shape of a row, but only if it is still the row that was normalized. */ private healRow; /** Records that a heal replaced one revision with another. */ private rememberHeal; /** Writes a new state only if the row still carries the `updatedAt` we read. */ private writeState; /** Whether the token a client is writing against still describes the row. */ private isStaleRevision; /** Every live row of a collection, payload included. */ private liveCollectionRows; /** The names a `where` keeps, resolved from the index table before a single row of content is read. */ private resolveFilter; private indexNames; private collectionEntryNames; private filteredCollectionRows; get(name: string, version?: EponymeVersionSelector): Promise | undefined>; getResult(name: string, version?: EponymeVersionSelector): Promise; /** Content as it was in a given version, for previewing without restoring it. */ private getVersionResult; statuses(): Promise>; /** Metadata keys that can be sorted on, alongside every field of the collection. */ collectionSortKeys(name: string): string[] | undefined; listCollection(name: string, version?: EponymeVersion, query?: EponymeCollectionQuery): Promise; /** * The unpaginated read, still cached: an unfiltered listing of one collection is what a page hits * repeatedly, and the key carries the version so a draft view cannot answer a public one. */ private collectionRows; /** * `findMany` already carries every payload, so the state is built here rather than re-read one entry at a * time: a listing costs one query, not N+1. */ private toCollectionEntries; /** Builds the public URL list configured by `previewPaths`. */ getSitemapEntries(previewPaths: Record): Promise; /** Every singleton and every live collection entry, as a portable file. */ exportContent(): Promise; /** * Applies an export file on top of the current content: every entry it carries is upserted, everything * else is left alone. */ importContent(file: unknown, options?: { dryRun?: boolean; actorId?: string; actorUsername?: string; }): Promise; /** Entries of a file that would actually be written: the others cannot satisfy a relation. */ private importableNames; /** Relations an export points at that nothing would satisfy. */ private importRelationErrors; /** * The body of an import, over whichever client it was handed: the live one for a dry run, a transaction * for the real thing. */ private applyImport; createCollectionEntry(name: string, payload: unknown, actor?: string | EponymeActor): Promise<(EponymeResult & { slug: string; errors?: never; }) | { errors: ValidationErrors; } | undefined>; /** * A trashed entry keeps its row, so it keeps its slug: reusing one has to be refused with an error the * editor can act on rather than the generic message. */ private slugTakenError; /** Live entries still pointing at this one, draft or published. */ findEponymeReferrers(entryName: string): Promise; /** * Whether a relation may point at `to`: a collection, or a folder whose direct children include * singletons - the stored value is then the singleton's name inside the folder. */ isRelationTarget(to: string): boolean; /** The singleton or collection entry a relation names, or `undefined` when nothing configured matches. */ private relationTargetKind; /** * Loads relation targets in one query per kind. `published` only answers what is live now; `draft` reads * the draft of the targets `draftAllowed` accepts and the live published version of the others, so a * preview never shows a target its reader may not open. */ loadRelationTargets(names: string[], options: { version: EponymeVersion; draftAllowed?: (name: string) => boolean; }): Promise>; /** Resolves the relations of `items`, `depth` levels deep, in one batch per level. */ populate(items: Array<{ schema: EponymeSchema; data: Record; }>, depth: number, options: { version: EponymeVersion; draftAllowed?: (name: string) => boolean; /** Applied to each target's data once loaded, before its own relations are walked. */ transform?: (name: string, schema: EponymeSchema | undefined, data: Record) => Record; }): Promise; /** * Singletons and collections whose schema declares a relation able to point at `target`, which is the set * of names whose publication can change who points at it. */ referrerSources(target: string): string[]; /** * The inverse of a relation: entries that point at `target`, read from the index rather than from the * content. `published` only returns referrers that are live and reference it in their published version. */ listReferrers(target: string, options?: { version?: EponymeVersion; collection?: string; }): Promise; /** Moves an entry to the trash. */ deleteCollectionEntry(name: string, actor?: string | EponymeActor, expectedRevision?: string): Promise<{ deleted: true; } | { referencedBy: string[]; } | EponymeConflict | undefined>; /** * Names every relation of a payload whose target is missing, so a reference can never be stored pointing * at nothing. */ private relationRejections; restoreCollectionEntry(name: string, actor?: string | EponymeActor, expectedRevision?: string, options?: EponymeRestoreOptions): Promise; /** Definitive: `onDelete: Cascade` takes the entry's whole history with it. */ purgeCollectionEntry(name: string, actor?: string | EponymeActor): Promise; /** Trashed entries of a collection, most recently updated first. */ listCollectionTrash(name: string): Promise; patch(name: string, payload: unknown, action?: EponymeAction, actor?: string | EponymeActor, schedule?: EponymeSchedule, expectedRevision?: string): Promise<(EponymeResult & { errors?: never; conflict?: never; }) | { errors: ValidationErrors; conflict?: never; } | EponymeConflict | undefined>; /** Materializes due dates for history, hooks and cache/CDN invalidation. */ runSchedule(now?: Date): Promise; history(name: string, limit?: number): Promise; restore(name: string, versionId: number, actor?: string | EponymeActor, expectedRevision?: string, options?: EponymeRestoreOptions): Promise; } /** Keeps a per-process bookkeeping collection finite, dropping the oldest keys first. */ export declare function capOldest(entries: { size: number; keys: () => IterableIterator; delete: (key: string) => boolean; }, max: number): void; /** Stable hash of a schema's shape, embedded in an export and checked on import. */ export declare function schemaFingerprint(schema: EponymeSchema): string; export declare function isPrismaError(error: unknown, code: string): boolean; /** The only in-memory definition of public visibility. */ export declare function isEponymeLive(state: Pick, now: Date): boolean; /** SQL translation of `isEponymeLive`; keep both changes together. */ export declare function eponymeLiveWhere(now: Date): PrismaEponymeWhere; /** The lock token an entry is read at: its `updatedAt`, as an ISO string. */ export declare function eponymeRevision(updatedAt: Date | string | undefined): string | null;