{"version":3,"file":"content-DCkaeV5Y.mjs","names":[],"sources":["../src/search/match.ts","../src/database/repositories/revision.ts","../src/database/repositories/content.ts"],"sourcesContent":["/**\n * FTS5 match-expression builder for structured (non-user-syntax) queries.\n *\n * Unlike `escapeQuery` in `query.ts` (which powers the public search API and\n * deliberately passes through FTS5 operators like AND/OR/NOT), this builder\n * treats the input as plain words: every term is double-quoted with interior\n * quotes escaped, so the result can never produce an FTS5 syntax error. Used\n * by the admin content-list filter, where the input is a filter box, not a\n * search-syntax field.\n */\n\nconst WHITESPACE_RE = /\\s+/;\nconst DOUBLE_QUOTE_RE = /\"/g;\nconst GLOB_SPECIAL_RE = /[[\\]*?]/g;\n\n/**\n * Build a prefix-matching FTS5 MATCH expression from free-form input.\n *\n * `hello wor` becomes `\"hello\"* \"wor\"*` — implicit AND with per-term prefix\n * matching. Returns `\"\"` when the input contains no usable terms; callers\n * must fall back to their non-FTS path in that case.\n */\nexport function buildFtsPrefixMatch(input: string): string {\n\tconst terms = input\n\t\t.trim()\n\t\t.split(WHITESPACE_RE)\n\t\t.map((term) => term.replace(DOUBLE_QUOTE_RE, '\"\"'))\n\t\t.filter((term) => term.length > 0);\n\n\tif (terms.length === 0) return \"\";\n\treturn terms.map((term) => `\"${term}\"*`).join(\" \");\n}\n\n/**\n * Build a GLOB prefix pattern from free-form input, treating GLOB\n * metacharacters (`* ? [ ]`) literally by wrapping each in a character\n * class (GLOB has no ESCAPE clause).\n *\n * GLOB (unlike default LIKE) is case-sensitive, so with a lowercased\n * pattern it matches slugs (lowercase by construction) while staying\n * servable by the ordinary BINARY-collated slug index — SQLite's GLOB\n * optimization turns a `prefix*` pattern into an index range scan.\n */\nexport function buildSlugGlobPrefix(input: string): string {\n\tconst escaped = input\n\t\t.trim()\n\t\t.toLowerCase()\n\t\t.replace(GLOB_SPECIAL_RE, (c) => `[${c}]`);\n\treturn `${escaped}*`;\n}\n","import { sql, type Kysely } from \"kysely\";\nimport { monotonicFactory } from \"ulidx\";\n\nimport type { Database, RevisionTable } from \"../types.js\";\nimport { validateIdentifier } from \"../validate.js\";\n\nconst monotonic = monotonicFactory();\n\nexport interface Revision {\n\tid: string;\n\tcollection: string;\n\tentryId: string;\n\tdata: Record<string, unknown>;\n\tauthorId: string | null;\n\tcreatedAt: string;\n}\n\nexport interface CreateRevisionInput {\n\tcollection: string;\n\tentryId: string;\n\tdata: Record<string, unknown>;\n\tauthorId?: string;\n}\n\n/**\n * Revision repository for version history\n *\n * Each revision stores a JSON snapshot of the content at a point in time.\n * Used when collection has `supports: [\"revisions\"]` enabled.\n */\nexport class RevisionRepository {\n\tconstructor(private db: Kysely<Database>) {}\n\n\t/**\n\t * Create a new revision\n\t */\n\tasync create(input: CreateRevisionInput): Promise<Revision> {\n\t\tconst id = monotonic();\n\n\t\tconst row: Omit<RevisionTable, \"created_at\"> = {\n\t\t\tid,\n\t\t\tcollection: input.collection,\n\t\t\tentry_id: input.entryId,\n\t\t\tdata: JSON.stringify(input.data),\n\t\t\tauthor_id: input.authorId ?? null,\n\t\t};\n\n\t\tawait this.db.insertInto(\"revisions\").values(row).execute();\n\n\t\tconst revision = await this.findById(id);\n\t\tif (!revision) {\n\t\t\tthrow new Error(\"Failed to create revision\");\n\t\t}\n\n\t\ttry {\n\t\t\tawait this.db\n\t\t\t\t.insertInto(\"_emdash_revision_prune_queue\")\n\t\t\t\t.values({\n\t\t\t\t\tcollection: input.collection,\n\t\t\t\t\tentry_id: input.entryId,\n\t\t\t\t\trevision_id: id,\n\t\t\t\t})\n\t\t\t\t.onConflict((conflict) =>\n\t\t\t\t\tconflict.columns([\"collection\", \"entry_id\"]).doUpdateSet({ revision_id: id }),\n\t\t\t\t)\n\t\t\t\t.execute();\n\t\t} catch (error) {\n\t\t\tconsole.error(\n\t\t\t\t`[revisions] Failed to queue revision pruning for ${input.collection}/${input.entryId}:`,\n\t\t\t\terror,\n\t\t\t);\n\t\t}\n\n\t\treturn revision;\n\t}\n\n\t/**\n\t * Find revision by ID\n\t */\n\tasync findById(id: string): Promise<Revision | null> {\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"revisions\")\n\t\t\t.selectAll()\n\t\t\t.where(\"id\", \"=\", id)\n\t\t\t.executeTakeFirst();\n\n\t\treturn row ? this.rowToRevision(row) : null;\n\t}\n\n\t/**\n\t * Get all revisions for an entry (newest first)\n\t *\n\t * Orders by monotonic ULID (descending). The monotonic factory\n\t * guarantees strictly increasing IDs even within the same millisecond.\n\t */\n\tasync findByEntry(\n\t\tcollection: string,\n\t\tentryId: string,\n\t\toptions: { limit?: number } = {},\n\t): Promise<Revision[]> {\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"revisions\")\n\t\t\t.selectAll()\n\t\t\t.where(\"collection\", \"=\", collection)\n\t\t\t.where(\"entry_id\", \"=\", entryId)\n\t\t\t.orderBy(\"id\", \"desc\");\n\n\t\tif (options.limit) {\n\t\t\tquery = query.limit(options.limit);\n\t\t}\n\n\t\tconst rows = await query.execute();\n\t\treturn rows.map((row) => this.rowToRevision(row));\n\t}\n\n\t/**\n\t * Get the most recent revision for an entry\n\t */\n\tasync findLatest(collection: string, entryId: string): Promise<Revision | null> {\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"revisions\")\n\t\t\t.selectAll()\n\t\t\t.where(\"collection\", \"=\", collection)\n\t\t\t.where(\"entry_id\", \"=\", entryId)\n\t\t\t.orderBy(\"id\", \"desc\")\n\t\t\t.limit(1)\n\t\t\t.executeTakeFirst();\n\n\t\treturn row ? this.rowToRevision(row) : null;\n\t}\n\n\t/**\n\t * Count revisions for an entry\n\t */\n\tasync countByEntry(collection: string, entryId: string): Promise<number> {\n\t\tconst result = await this.db\n\t\t\t.selectFrom(\"revisions\")\n\t\t\t.select((eb) => eb.fn.count(\"id\").as(\"count\"))\n\t\t\t.where(\"collection\", \"=\", collection)\n\t\t\t.where(\"entry_id\", \"=\", entryId)\n\t\t\t.executeTakeFirst();\n\n\t\treturn Number(result?.count || 0);\n\t}\n\n\t/**\n\t * Delete all revisions for an entry (use when entry is deleted)\n\t */\n\tasync deleteByEntry(collection: string, entryId: string): Promise<number> {\n\t\tconst result = await this.db\n\t\t\t.deleteFrom(\"revisions\")\n\t\t\t.where(\"collection\", \"=\", collection)\n\t\t\t.where(\"entry_id\", \"=\", entryId)\n\t\t\t.executeTakeFirst();\n\n\t\ttry {\n\t\t\tawait this.db\n\t\t\t\t.deleteFrom(\"_emdash_revision_prune_queue\")\n\t\t\t\t.where(\"collection\", \"=\", collection)\n\t\t\t\t.where(\"entry_id\", \"=\", entryId)\n\t\t\t\t.execute();\n\t\t} catch (error) {\n\t\t\tconsole.error(\n\t\t\t\t`[revisions] Failed to clear queued revision pruning for ${collection}/${entryId}:`,\n\t\t\t\terror,\n\t\t\t);\n\t\t}\n\n\t\treturn Number(result.numDeletedRows ?? 0);\n\t}\n\n\t/**\n\t * Delete old revisions, keeping the most recent N\n\t */\n\tasync pruneOldRevisions(\n\t\tcollection: string,\n\t\tentryId: string,\n\t\tkeepCount: number,\n\t\tthroughRevisionId?: string,\n\t): Promise<number> {\n\t\tvalidateIdentifier(collection, \"collection\");\n\t\tconst tableName = `ec_${collection}`;\n\t\tlet keepQuery = this.db\n\t\t\t.selectFrom(\"revisions\")\n\t\t\t.select(\"id\")\n\t\t\t.where(\"collection\", \"=\", collection)\n\t\t\t.where(\"entry_id\", \"=\", entryId)\n\t\t\t.orderBy(\"created_at\", \"desc\")\n\t\t\t.orderBy(\"id\", \"desc\") // ULID tiebreaker\n\t\t\t.limit(keepCount);\n\n\t\tif (throughRevisionId) {\n\t\t\tkeepQuery = keepQuery.where(\"id\", \"<=\", throughRevisionId);\n\t\t}\n\n\t\tconst keep = await keepQuery.execute();\n\n\t\tconst keepIds = keep.map((r) => r.id);\n\n\t\tif (keepIds.length === 0) return 0;\n\t\tconst revisionBoundary = throughRevisionId ? sql`AND id <= ${throughRevisionId}` : sql``;\n\n\t\tconst result = await sql`\n\t\t\tDELETE FROM revisions\n\t\t\tWHERE collection = ${collection}\n\t\t\tAND entry_id = ${entryId}\n\t\t\t${revisionBoundary}\n\t\t\tAND id NOT IN (${sql.join(keepIds.map((id) => sql`${id}`))})\n\t\t\tAND NOT EXISTS (\n\t\t\t\tSELECT 1 FROM ${sql.ref(tableName)} AS content\n\t\t\t\tWHERE content.live_revision_id = revisions.id\n\t\t\t\tOR content.draft_revision_id = revisions.id\n\t\t\t)\n\t\t`.execute(this.db);\n\n\t\treturn Number(result.numAffectedRows ?? 0);\n\t}\n\n\tasync pruneQueuedEntry(\n\t\tcollection: string,\n\t\tentryId: string,\n\t\tqueuedRevisionId: string,\n\t\tkeepCount: number,\n\t): Promise<number> {\n\t\tconst pruned = await this.pruneOldRevisions(collection, entryId, keepCount, queuedRevisionId);\n\t\tawait this.db\n\t\t\t.deleteFrom(\"_emdash_revision_prune_queue\")\n\t\t\t.where(\"collection\", \"=\", collection)\n\t\t\t.where(\"entry_id\", \"=\", entryId)\n\t\t\t.where(\"revision_id\", \"=\", queuedRevisionId)\n\t\t\t.execute();\n\t\treturn pruned;\n\t}\n\n\tasync deleteIfUnreferenced(\n\t\tcollection: string,\n\t\tentryId: string,\n\t\trevisionId: string,\n\t): Promise<boolean> {\n\t\tvalidateIdentifier(collection, \"collection\");\n\t\tconst tableName = `ec_${collection}`;\n\t\tconst result = await sql`\n\t\t\tDELETE FROM revisions\n\t\t\tWHERE id = ${revisionId}\n\t\t\tAND collection = ${collection}\n\t\t\tAND entry_id = ${entryId}\n\t\t\tAND NOT EXISTS (\n\t\t\t\tSELECT 1 FROM ${sql.ref(tableName)} AS content\n\t\t\t\tWHERE content.live_revision_id = revisions.id\n\t\t\t\tOR content.draft_revision_id = revisions.id\n\t\t\t)\n\t\t`.execute(this.db);\n\t\treturn (result.numAffectedRows ?? 0n) > 0n;\n\t}\n\n\t/**\n\t * Convert database row to Revision object\n\t */\n\tprivate rowToRevision(row: {\n\t\tid: string;\n\t\tcollection: string;\n\t\tentry_id: string;\n\t\tdata: string;\n\t\tauthor_id: string | null;\n\t\tcreated_at: string;\n\t}): Revision {\n\t\treturn {\n\t\t\tid: row.id,\n\t\t\tcollection: row.collection,\n\t\t\tentryId: row.entry_id,\n\t\t\tdata: JSON.parse(row.data),\n\t\t\tauthorId: row.author_id,\n\t\t\tcreatedAt: row.created_at,\n\t\t};\n\t}\n}\n","import { sql, type Kysely } from \"kysely\";\nimport { ulid } from \"ulidx\";\n\nimport type { ContentFieldFilterValue, ContentFieldFilters } from \"../../content-list-query.js\";\nimport { invalidateCollectionCache } from \"../../object-cache/index.js\";\nimport { isIndexableFieldType, type FieldType } from \"../../schema/types.js\";\nimport { buildFtsPrefixMatch, buildSlugGlobPrefix } from \"../../search/match.js\";\nimport { chunks, SQL_BATCH_SIZE } from \"../../utils/chunks.js\";\nimport { isMissingTableError } from \"../../utils/db-errors.js\";\nimport { slugify } from \"../../utils/slugify.js\";\nimport type { Database } from \"../types.js\";\nimport { validateIdentifier } from \"../validate.js\";\nimport { RevisionRepository } from \"./revision.js\";\nimport type {\n\tCreateContentInput,\n\tUpdateContentInput,\n\tFindManyOptions,\n\tFindManyResult,\n\tContentItem,\n\tContentDateField,\n\tContentBylineFilter,\n} from \"./types.js\";\nimport {\n\tContentCollectionNotFoundError,\n\tContentMutationConflictError,\n\tEmDashValidationError,\n\tInvalidCursorError,\n\tScheduledNotDueError,\n\tencodeCursor,\n\tdecodeCursor,\n} from \"./types.js\";\n\n// Regex pattern for ULID validation\nconst ULID_PATTERN = /^[0-9A-Z]{26}$/;\nconst SQLSTATE_PATTERN = /^[0-9A-Z]{5}$/;\nconst MAX_DRAFT_STAGE_ATTEMPTS = 32;\n\n// LIKE wildcards that must be escaped so user search input is matched literally.\nconst LIKE_WILDCARD_RE = /[\\\\%_]/g;\nconst MAX_INDEXED_FIELD_FILTERS = 20;\nconst MAX_IN_FILTER_VALUES = SQL_BATCH_SIZE;\nconst MAX_FILTER_STRING_LENGTH = 2048;\n\ntype NormalizedFilterScalar = string | number;\n\ntype ResolvedFieldFilter =\n\t| { column: string; kind: \"null\" }\n\t| { column: string; kind: \"exact\"; value: NormalizedFilterScalar }\n\t| { column: string; kind: \"in\"; values: NormalizedFilterScalar[] }\n\t| {\n\t\t\tcolumn: string;\n\t\t\tkind: \"range\";\n\t\t\tbounds: Partial<Record<\"gt\" | \"gte\" | \"lt\" | \"lte\", NormalizedFilterScalar>>;\n\t  };\n\nfunction nullableColumnMatch(column: string, value: string | null): ReturnType<typeof sql> {\n\tvalidateIdentifier(column, \"content column\");\n\treturn value === null ? sql`${sql.ref(column)} IS NULL` : sql`${sql.ref(column)} = ${value}`;\n}\n\nfunction sameStoredValue(left: unknown, right: unknown): boolean {\n\treturn Object.is(serializeValue(left), serializeValue(right));\n}\n\nfunction matchesPublication(\n\tobserved: ContentItem,\n\texisting: ContentItem,\n\trevision: { data: Record<string, unknown> },\n\trevisionId: string,\n\tslug: string | null,\n\tpublishedAt: string,\n\tupdatedAt: string,\n): boolean {\n\tif (\n\t\tobserved.version !== existing.version + 1 ||\n\t\tobserved.status !== \"published\" ||\n\t\tobserved.slug !== slug ||\n\t\tobserved.liveRevisionId !== revisionId ||\n\t\tobserved.draftRevisionId !== null ||\n\t\tobserved.scheduledAt !== null ||\n\t\tobserved.publishedAt !== publishedAt ||\n\t\tobserved.updatedAt !== updatedAt\n\t) {\n\t\treturn false;\n\t}\n\n\treturn Object.entries(revision.data).every(\n\t\t([key, value]) =>\n\t\t\tSYSTEM_COLUMNS.has(key) || key.startsWith(\"_\") || sameStoredValue(observed.data[key], value),\n\t);\n}\n\nfunction matchesLifecyclePublication(\n\tobserved: ContentItem,\n\texisting: ContentItem,\n\tliveRevisionId: string,\n\tpublishedAt: string,\n\tupdatedAt: string,\n): boolean {\n\tif (\n\t\tobserved.version !== existing.version + 1 ||\n\t\tobserved.status !== \"published\" ||\n\t\tobserved.slug !== existing.slug ||\n\t\tobserved.liveRevisionId !== liveRevisionId ||\n\t\tobserved.draftRevisionId !== null ||\n\t\tobserved.scheduledAt !== null ||\n\t\tobserved.publishedAt !== publishedAt ||\n\t\tobserved.updatedAt !== updatedAt\n\t) {\n\t\treturn false;\n\t}\n\n\treturn Object.entries(existing.data).every(([key, value]) =>\n\t\tsameStoredValue(observed.data[key], value),\n\t);\n}\n\nfunction matchesPublicationFence(observed: ContentItem, existing: ContentItem): boolean {\n\treturn (\n\t\tobserved.version === existing.version &&\n\t\tobserved.status === existing.status &&\n\t\tobserved.liveRevisionId === existing.liveRevisionId &&\n\t\tobserved.draftRevisionId === existing.draftRevisionId &&\n\t\tobserved.scheduledAt === existing.scheduledAt\n\t);\n}\n\nfunction isConfirmedStatementFailure(error: unknown): boolean {\n\tif (typeof error !== \"object\" || error === null || !(\"code\" in error)) return false;\n\tconst code = (error as { code?: unknown }).code;\n\treturn typeof code === \"string\" && (code.startsWith(\"SQLITE_\") || SQLSTATE_PATTERN.test(code));\n}\n\ninterface ResolvedOrderField {\n\tcolumn: string;\n\tindexedCustomField: boolean;\n}\n\ntype IndexedOrderValue = string | number | null;\n\ninterface IndexedFieldCursorPayload {\n\tversion: 1;\n\tfield: string;\n\tvalue: IndexedOrderValue;\n}\n\nfunction encodeIndexedFieldCursor(field: string, value: IndexedOrderValue, id: string): string {\n\tconst payload: IndexedFieldCursorPayload = { version: 1, field, value };\n\treturn encodeCursor(JSON.stringify(payload), id);\n}\n\nfunction decodeIndexedFieldCursor(\n\tcursor: string,\n\tfield: string,\n): { value: IndexedOrderValue; id: string } {\n\tconst { orderValue, id } = decodeCursor(cursor);\n\tlet payload: unknown;\n\ttry {\n\t\tpayload = JSON.parse(orderValue);\n\t} catch {\n\t\tthrow new InvalidCursorError(cursor);\n\t}\n\n\tif (payload === null || typeof payload !== \"object\") {\n\t\tthrow new InvalidCursorError(cursor);\n\t}\n\tconst candidate = payload as Partial<IndexedFieldCursorPayload>;\n\tconst validValue =\n\t\tcandidate.value === null ||\n\t\ttypeof candidate.value === \"string\" ||\n\t\ttypeof candidate.value === \"number\";\n\tif (candidate.version !== 1 || candidate.field !== field || !validValue) {\n\t\tthrow new InvalidCursorError(cursor);\n\t}\n\n\treturn { value: candidate.value as IndexedOrderValue, id };\n}\n\n/**\n * Whitelist mapping a public date-filter field to its physical column. Keeping\n * this separate from `mapOrderField` makes the filterable set explicit and\n * prevents filtering on arbitrary columns.\n */\nconst DATE_FILTER_COLUMNS: Record<ContentDateField, \"created_at\" | \"updated_at\" | \"published_at\"> =\n\t{\n\t\tcreatedAt: \"created_at\",\n\t\tupdatedAt: \"updated_at\",\n\t\tpublishedAt: \"published_at\",\n\t};\n\n/**\n * Built-in sort fields → their physical columns. A closed set that blocks\n * sorting by arbitrary columns; per-collection fields are allowed\n * separately via `mapOrderField`'s `sortableExtras`.\n */\nconst ORDER_FIELD_COLUMNS: Record<string, string> = {\n\tcreatedAt: \"created_at\",\n\tupdatedAt: \"updated_at\",\n\tpublishedAt: \"published_at\",\n\tscheduledAt: \"scheduled_at\",\n\tdeletedAt: \"deleted_at\",\n\ttitle: \"title\",\n\tname: \"name\",\n\tslug: \"slug\",\n\tstatus: \"status\",\n\tlocale: \"locale\",\n};\n\n/** True when `field` maps to a system column and needs no per-collection resolution. */\nexport function isSystemOrderField(field: string): boolean {\n\treturn field in ORDER_FIELD_COLUMNS;\n}\n\n/**\n * System columns that exist in every ec_* table\n */\nconst SYSTEM_COLUMNS = new Set([\n\t\"id\",\n\t\"slug\",\n\t\"status\",\n\t\"author_id\",\n\t\"primary_byline_id\",\n\t\"created_at\",\n\t\"updated_at\",\n\t\"published_at\",\n\t\"scheduled_at\",\n\t\"deleted_at\",\n\t\"version\",\n\t\"live_revision_id\",\n\t\"draft_revision_id\",\n\t\"locale\",\n\t\"translation_group\",\n]);\n\n/**\n * Get the table name for a collection type\n */\nfunction getTableName(type: string): string {\n\tvalidateIdentifier(type, \"collection type\");\n\treturn `ec_${type}`;\n}\n\n/**\n * Serialize a value for database storage\n * Objects/arrays are JSON-stringified\n * Booleans are converted to 0/1 for SQLite\n */\nfunction serializeValue(value: unknown): unknown {\n\tif (value === null || value === undefined) {\n\t\treturn null;\n\t}\n\tif (typeof value === \"boolean\") {\n\t\treturn value ? 1 : 0;\n\t}\n\tif (typeof value === \"object\") {\n\t\treturn JSON.stringify(value);\n\t}\n\treturn value;\n}\n\nfunction writableContentData(data: Record<string, unknown>): Record<string, unknown> {\n\tconst writable: Record<string, unknown> = {};\n\tfor (const [key, value] of Object.entries(data)) {\n\t\tif (SYSTEM_COLUMNS.has(key)) continue;\n\t\tvalidateIdentifier(key, \"content field name\");\n\t\twritable[key] = value;\n\t}\n\treturn writable;\n}\n\n/**\n * Deserialize a value from database storage\n * Attempts to parse JSON strings that look like objects/arrays\n */\nfunction deserializeValue(value: unknown): unknown {\n\tif (typeof value === \"string\") {\n\t\t// Try to parse if it looks like JSON\n\t\tif (value.startsWith(\"{\") || value.startsWith(\"[\")) {\n\t\t\ttry {\n\t\t\t\treturn JSON.parse(value);\n\t\t\t} catch {\n\t\t\t\treturn value;\n\t\t\t}\n\t\t}\n\t}\n\treturn value;\n}\n\n/** Pattern for escaping special regex characters */\nconst REGEX_ESCAPE_PATTERN = /[.*+?^${}()|[\\]\\\\]/g;\n\n/**\n * Escape special regex characters in a string for use in `new RegExp()`\n */\nfunction escapeRegExp(s: string): string {\n\treturn s.replace(REGEX_ESCAPE_PATTERN, \"\\\\$&\");\n}\n\n/**\n * Repository for content CRUD operations\n *\n * Content is stored in per-collection tables (ec_posts, ec_pages, etc.)\n * Each field becomes a real column in the table.\n */\nexport class ContentRepository {\n\tconstructor(private db: Kysely<Database>) {}\n\n\t/**\n\t * Create a new content item\n\t */\n\tasync create(input: CreateContentInput): Promise<ContentItem> {\n\t\tconst id = input.id ?? ulid();\n\t\tconst now = new Date().toISOString();\n\n\t\tconst {\n\t\t\ttype,\n\t\t\tslug,\n\t\t\tdata,\n\t\t\tstatus = \"draft\",\n\t\t\tauthorId,\n\t\t\tprimaryBylineId,\n\t\t\tlocale,\n\t\t\ttranslationOf,\n\t\t\tpublishedAt,\n\t\t\tcreatedAt,\n\t\t} = input;\n\n\t\t// Validate required fields\n\t\tif (!type) {\n\t\t\tthrow new EmDashValidationError(\"Content type is required\");\n\t\t}\n\n\t\tconst tableName = getTableName(type);\n\n\t\t// Resolve translation_group: if translationOf is set, look up the source item's group\n\t\tlet translationGroup: string = id; // default: self-reference\n\t\tif (translationOf) {\n\t\t\tconst source = await this.findById(type, translationOf);\n\t\t\tif (!source) {\n\t\t\t\tthrow new EmDashValidationError(\"Translation source content not found\");\n\t\t\t}\n\t\t\ttranslationGroup = source.translationGroup || source.id;\n\t\t}\n\n\t\t// Build column names and values\n\t\tconst columns: string[] = [\n\t\t\t\"id\",\n\t\t\t\"slug\",\n\t\t\t\"status\",\n\t\t\t\"author_id\",\n\t\t\t\"primary_byline_id\",\n\t\t\t\"created_at\",\n\t\t\t\"updated_at\",\n\t\t\t\"published_at\",\n\t\t\t\"version\",\n\t\t\t\"locale\",\n\t\t\t\"translation_group\",\n\t\t];\n\t\tconst values: unknown[] = [\n\t\t\tid,\n\t\t\tslug || null,\n\t\t\tstatus,\n\t\t\tauthorId || null,\n\t\t\tprimaryBylineId ?? null,\n\t\t\tcreatedAt || now,\n\t\t\tnow,\n\t\t\tpublishedAt || null,\n\t\t\t1,\n\t\t\tlocale || \"en\",\n\t\t\ttranslationGroup,\n\t\t];\n\n\t\t// Add data fields as columns (skip system columns to prevent injection via data)\n\t\tif (data && typeof data === \"object\") {\n\t\t\tfor (const [key, value] of Object.entries(data)) {\n\t\t\t\tif (!SYSTEM_COLUMNS.has(key)) {\n\t\t\t\t\tvalidateIdentifier(key, \"content field name\");\n\t\t\t\t\tcolumns.push(key);\n\t\t\t\t\tvalues.push(serializeValue(value));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Build dynamic INSERT using raw SQL\n\t\tconst columnRefs = columns.map((c) => sql.ref(c));\n\t\tconst valuePlaceholders = values.map((v) => (v === null ? sql`NULL` : sql`${v}`));\n\n\t\tawait sql`\n\t\t\tINSERT INTO ${sql.ref(tableName)} (${sql.join(columnRefs, sql`, `)})\n\t\t\tVALUES (${sql.join(valuePlaceholders, sql`, `)})\n\t\t`.execute(this.db);\n\n\t\tinvalidateCollectionCache(type);\n\n\t\t// Fetch and return the created item\n\t\tconst item = await this.findById(type, id);\n\t\tif (!item) {\n\t\t\tthrow new Error(\"Failed to create content\");\n\t\t}\n\t\treturn item;\n\t}\n\n\t/**\n\t * Generate a unique slug for a content item within a collection.\n\t *\n\t * Checks the collection table for existing slugs that match `baseSlug`\n\t * (optionally scoped to a locale) and appends a numeric suffix (`-1`,\n\t * `-2`, etc.) on collision to guarantee uniqueness.\n\t *\n\t * Returns null when slug normalization cannot produce a value.\n\t */\n\tasync generateUniqueSlug(type: string, text: string, locale?: string): Promise<string | null> {\n\t\tconst baseSlug = slugify(text);\n\t\tif (!baseSlug) return null;\n\n\t\tconst tableName = getTableName(type);\n\n\t\t// Check if the base slug is available\n\t\tconst existing = locale\n\t\t\t? await sql<{ slug: string }>`\n\t\t\t\t\tSELECT slug FROM ${sql.ref(tableName)}\n\t\t\t\t\tWHERE slug = ${baseSlug}\n\t\t\t\t\tAND locale = ${locale}\n\t\t\t\t\tLIMIT 1\n\t\t\t\t`.execute(this.db)\n\t\t\t: await sql<{ slug: string }>`\n\t\t\t\t\tSELECT slug FROM ${sql.ref(tableName)}\n\t\t\t\t\tWHERE slug = ${baseSlug}\n\t\t\t\t\tLIMIT 1\n\t\t\t\t`.execute(this.db);\n\n\t\tif (existing.rows.length === 0) {\n\t\t\treturn baseSlug;\n\t\t}\n\n\t\t// Find all slugs matching the pattern `baseSlug` or `baseSlug-N`\n\t\tconst pattern = `${baseSlug}-%`;\n\t\tconst candidates = locale\n\t\t\t? await sql<{ slug: string }>`\n\t\t\t\t\tSELECT slug FROM ${sql.ref(tableName)}\n\t\t\t\t\tWHERE (slug = ${baseSlug} OR slug LIKE ${pattern})\n\t\t\t\t\tAND locale = ${locale}\n\t\t\t\t`.execute(this.db)\n\t\t\t: await sql<{ slug: string }>`\n\t\t\t\t\tSELECT slug FROM ${sql.ref(tableName)}\n\t\t\t\t\tWHERE slug = ${baseSlug} OR slug LIKE ${pattern}\n\t\t\t\t`.execute(this.db);\n\n\t\t// Find the highest numeric suffix in use\n\t\tlet maxSuffix = 0;\n\t\tconst suffixPattern = new RegExp(`^${escapeRegExp(baseSlug)}-(\\\\d+)$`);\n\t\tfor (const row of candidates.rows) {\n\t\t\tconst match = suffixPattern.exec(row.slug);\n\t\t\tif (match) {\n\t\t\t\tconst n = parseInt(match[1], 10);\n\t\t\t\tif (n > maxSuffix) maxSuffix = n;\n\t\t\t}\n\t\t}\n\n\t\treturn `${baseSlug}-${maxSuffix + 1}`;\n\t}\n\n\t/**\n\t * Duplicate a content item\n\t * Creates a new draft copy with \"(Copy)\" appended to the title.\n\t * A slug is auto-generated from the new title by the handler layer.\n\t */\n\tasync duplicate(type: string, id: string, authorId?: string): Promise<ContentItem> {\n\t\t// Fetch the original item\n\t\tconst original = await this.findById(type, id);\n\t\tif (!original) {\n\t\t\tthrow new EmDashValidationError(\"Content item not found\");\n\t\t}\n\n\t\t// Prepare the new data\n\t\tconst newData = { ...original.data };\n\n\t\t// Append \"(Copy)\" to title if present\n\t\tif (typeof newData.title === \"string\") {\n\t\t\tnewData.title = `${newData.title} (Copy)`;\n\t\t} else if (typeof newData.name === \"string\") {\n\t\t\tnewData.name = `${newData.name} (Copy)`;\n\t\t}\n\n\t\t// Auto-generate a unique slug from the new title/name\n\t\tconst slugSource =\n\t\t\ttypeof newData.title === \"string\"\n\t\t\t\t? newData.title\n\t\t\t\t: typeof newData.name === \"string\"\n\t\t\t\t\t? newData.name\n\t\t\t\t\t: null;\n\n\t\tconst slug = slugSource\n\t\t\t? await this.generateUniqueSlug(type, slugSource, original.locale ?? undefined)\n\t\t\t: null;\n\n\t\t// Create the duplicate as a draft — use override authorId if provided (caller owns the copy)\n\t\treturn this.create({\n\t\t\ttype,\n\t\t\tslug,\n\t\t\tdata: newData,\n\t\t\tstatus: \"draft\",\n\t\t\tauthorId: authorId || original.authorId || undefined,\n\t\t\tlocale: original.locale ?? undefined,\n\t\t});\n\t}\n\n\t/**\n\t * Find content by ID\n\t */\n\tasync findById(type: string, id: string): Promise<ContentItem | null> {\n\t\tconst tableName = getTableName(type);\n\n\t\tconst result = await sql<Record<string, unknown>>`\n\t\t\tSELECT * FROM ${sql.ref(tableName)}\n\t\t\tWHERE id = ${id}\n\t\t\tAND deleted_at IS NULL\n\t\t`.execute(this.db);\n\n\t\tconst row = result.rows[0];\n\t\tif (!row) {\n\t\t\treturn null;\n\t\t}\n\n\t\treturn this.mapRow(type, row);\n\t}\n\n\t/**\n\t * Find content by id, including trashed (soft-deleted) items.\n\t * Used by restore endpoint for ownership checks.\n\t */\n\tasync findByIdIncludingTrashed(type: string, id: string): Promise<ContentItem | null> {\n\t\tconst tableName = getTableName(type);\n\n\t\tconst result = await sql<Record<string, unknown>>`\n\t\t\tSELECT * FROM ${sql.ref(tableName)}\n\t\t\tWHERE id = ${id}\n\t\t`.execute(this.db);\n\n\t\tconst row = result.rows[0];\n\t\tif (!row) {\n\t\t\treturn null;\n\t\t}\n\n\t\treturn this.mapRow(type, row);\n\t}\n\n\t/**\n\t * Find content by ID or slug. Tries ID first if it looks like a ULID,\n\t * otherwise tries slug. Falls back to the other if the first lookup misses.\n\t */\n\tasync findByIdOrSlug(\n\t\ttype: string,\n\t\tidentifier: string,\n\t\tlocale?: string,\n\t): Promise<ContentItem | null> {\n\t\treturn this._findByIdOrSlug(type, identifier, false, locale);\n\t}\n\n\t/**\n\t * Find content by ID or slug, including trashed (soft-deleted) items.\n\t * Used by restore/permanent-delete endpoints.\n\t */\n\tasync findByIdOrSlugIncludingTrashed(\n\t\ttype: string,\n\t\tidentifier: string,\n\t\tlocale?: string,\n\t): Promise<ContentItem | null> {\n\t\treturn this._findByIdOrSlug(type, identifier, true, locale);\n\t}\n\n\tprivate async _findByIdOrSlug(\n\t\ttype: string,\n\t\tidentifier: string,\n\t\tincludeTrashed: boolean,\n\t\tlocale?: string,\n\t): Promise<ContentItem | null> {\n\t\t// ULIDs are 26 uppercase alphanumeric chars\n\t\tconst looksLikeUlid = ULID_PATTERN.test(identifier);\n\n\t\tconst findById = includeTrashed\n\t\t\t? (t: string, id: string) => this.findByIdIncludingTrashed(t, id)\n\t\t\t: (t: string, id: string) => this.findById(t, id);\n\t\tconst findBySlug = includeTrashed\n\t\t\t? (t: string, s: string) => this.findBySlugIncludingTrashed(t, s, locale)\n\t\t\t: (t: string, s: string) => this.findBySlug(t, s, locale);\n\n\t\ttry {\n\t\t\tif (looksLikeUlid) {\n\t\t\t\t// Try ID first, fall back to slug\n\t\t\t\tconst byId = await findById(type, identifier);\n\t\t\t\tif (byId) return byId;\n\t\t\t\treturn await findBySlug(type, identifier);\n\t\t\t}\n\t\t\t// Try slug first, fall back to ID\n\t\t\tconst bySlug = await findBySlug(type, identifier);\n\t\t\tif (bySlug) return bySlug;\n\t\t\treturn await findById(type, identifier);\n\t\t} catch (error) {\n\t\t\t// A collection dropped out from under a still-referencing caller (e.g. a\n\t\t\t// relation whose collection was deleted without cascading) leaves the\n\t\t\t// ec_* table missing. Treat that as \"not found\", matching\n\t\t\t// findManyByIdOrSlug and findTranslationsForGroups, so callers surface a\n\t\t\t// structured NOT_FOUND instead of a 500.\n\t\t\tif (isMissingTableError(error)) return null;\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/**\n\t * Find content by slug\n\t */\n\tasync findBySlug(type: string, slug: string, locale?: string): Promise<ContentItem | null> {\n\t\tconst tableName = getTableName(type);\n\n\t\tconst result = locale\n\t\t\t? await sql<Record<string, unknown>>`\n\t\t\t\t\tSELECT * FROM ${sql.ref(tableName)}\n\t\t\t\t\tWHERE slug = ${slug}\n\t\t\t\t\tAND locale = ${locale}\n\t\t\t\t\tAND deleted_at IS NULL\n\t\t\t\t`.execute(this.db)\n\t\t\t: await sql<Record<string, unknown>>`\n\t\t\t\t\tSELECT * FROM ${sql.ref(tableName)}\n\t\t\t\t\tWHERE slug = ${slug}\n\t\t\t\t\tAND deleted_at IS NULL\n\t\t\t\t\tORDER BY locale ASC\n\t\t\t\t\tLIMIT 1\n\t\t\t\t`.execute(this.db);\n\n\t\tconst row = result.rows[0];\n\t\tif (!row) {\n\t\t\treturn null;\n\t\t}\n\n\t\treturn this.mapRow(type, row);\n\t}\n\n\t/**\n\t * Find content by slug, including trashed (soft-deleted) items.\n\t * Used by restore/permanent-delete endpoints.\n\t */\n\tasync findBySlugIncludingTrashed(\n\t\ttype: string,\n\t\tslug: string,\n\t\tlocale?: string,\n\t): Promise<ContentItem | null> {\n\t\tconst tableName = getTableName(type);\n\n\t\tconst result = locale\n\t\t\t? await sql<Record<string, unknown>>`\n\t\t\t\t\tSELECT * FROM ${sql.ref(tableName)}\n\t\t\t\t\tWHERE slug = ${slug}\n\t\t\t\t\tAND locale = ${locale}\n\t\t\t\t`.execute(this.db)\n\t\t\t: await sql<Record<string, unknown>>`\n\t\t\t\t\tSELECT * FROM ${sql.ref(tableName)}\n\t\t\t\t\tWHERE slug = ${slug}\n\t\t\t\t\tORDER BY locale ASC\n\t\t\t\t\tLIMIT 1\n\t\t\t\t`.execute(this.db);\n\n\t\tconst row = result.rows[0];\n\t\tif (!row) {\n\t\t\treturn null;\n\t\t}\n\n\t\treturn this.mapRow(type, row);\n\t}\n\n\t/**\n\t * Find many content items with filtering and pagination\n\t */\n\tasync findMany(\n\t\ttype: string,\n\t\toptions: FindManyOptions = {},\n\t): Promise<FindManyResult<ContentItem>> {\n\t\tconst tableName = getTableName(type);\n\t\tconst limit = Math.min(options.limit || 50, 100);\n\n\t\t// Determine ordering\n\t\tconst orderField = options.orderBy?.field || \"createdAt\";\n\t\tconst orderDirection = options.orderBy?.direction || \"desc\";\n\t\tconst resolvedOrderField = await this.resolveOrderField(\n\t\t\ttype,\n\t\t\torderField,\n\t\t\toptions.sortableExtras,\n\t\t);\n\t\tconst dbField = resolvedOrderField.column;\n\t\tconst resolvedFieldFilters = await this.resolveFieldFilters(type, options.where?.fieldFilters);\n\n\t\t// Validate order direction to prevent injection\n\t\tconst safeOrderDirection = orderDirection.toLowerCase() === \"asc\" ? \"ASC\" : \"DESC\";\n\n\t\t// Build query with parameterized values (no string interpolation)\n\t\t// Note: Dynamic content tables have deleted_at column, cast needed for Kysely\n\t\tlet query = this.db\n\t\t\t.selectFrom(tableName as keyof Database)\n\t\t\t.selectAll()\n\t\t\t.where(\"deleted_at\" as never, \"is\", null);\n\n\t\t// Apply filters with parameterized queries\n\t\tif (options.where?.status) {\n\t\t\tquery = query.where(\"status\", \"=\", options.where.status);\n\t\t}\n\n\t\tif (options.where?.authorId) {\n\t\t\tquery = query.where(\"author_id\", \"=\", options.where.authorId);\n\t\t}\n\n\t\tif (options.where?.locale) {\n\t\t\tquery = query.where(\"locale\" as any, \"=\", options.where.locale);\n\t\t}\n\n\t\tquery = this.applySearchFilter(query, options.where, type);\n\t\tquery = this.applyDateFilter(query, options.where);\n\t\tquery = this.applyBylineFilter(query, options.where, type);\n\t\tquery = this.applyFieldFilters(query, resolvedFieldFilters);\n\n\t\t// Handle cursor pagination — decodeCursor throws InvalidCursorError\n\t\t// on malformed input; let it propagate so handlers surface a\n\t\t// structured INVALID_CURSOR rather than silently returning page 1.\n\t\tif (options.cursor) {\n\t\t\tif (resolvedOrderField.indexedCustomField) {\n\t\t\t\tconst { value, id: cursorId } = decodeIndexedFieldCursor(options.cursor, orderField);\n\t\t\t\tconst isPresent = sql<boolean>`${sql.ref(dbField)} IS NOT NULL`;\n\t\t\t\tconst falseLiteral = sql<boolean>`FALSE`;\n\t\t\t\tconst trueLiteral = sql<boolean>`TRUE`;\n\t\t\t\tif (safeOrderDirection === \"ASC\" && value === null) {\n\t\t\t\t\tquery = query.where(sql<boolean>`\n\t\t\t\t\t\t(${isPresent}) > ${falseLiteral}\n\t\t\t\t\t\tOR ((${isPresent}) = ${falseLiteral} AND ${sql.ref(\"id\")} > ${cursorId})\n\t\t\t\t\t`);\n\t\t\t\t} else if (safeOrderDirection === \"DESC\" && value === null) {\n\t\t\t\t\tquery = query.where(sql<boolean>`\n\t\t\t\t\t\t(${isPresent}) = ${falseLiteral} AND ${sql.ref(\"id\")} < ${cursorId}\n\t\t\t\t\t`);\n\t\t\t\t} else if (safeOrderDirection === \"ASC\") {\n\t\t\t\t\tquery = query.where(sql<boolean>`\n\t\t\t\t\t\t(${isPresent}, ${sql.ref(dbField)}, ${sql.ref(\"id\")})\n\t\t\t\t\t\t\t> (${trueLiteral}, ${value}, ${cursorId})\n\t\t\t\t\t`);\n\t\t\t\t} else {\n\t\t\t\t\tquery = query.where(sql<boolean>`\n\t\t\t\t\t\t(${isPresent}, ${sql.ref(dbField)}, ${sql.ref(\"id\")})\n\t\t\t\t\t\t\t< (${trueLiteral}, ${value}, ${cursorId})\n\t\t\t\t\t`);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tconst { orderValue, id: cursorId } = decodeCursor(options.cursor);\n\n\t\t\t\tif (safeOrderDirection === \"DESC\") {\n\t\t\t\t\tquery = query.where((eb) =>\n\t\t\t\t\t\teb.or([\n\t\t\t\t\t\t\teb(dbField as any, \"<\", orderValue),\n\t\t\t\t\t\t\teb.and([eb(dbField as any, \"=\", orderValue), eb(\"id\", \"<\", cursorId)]),\n\t\t\t\t\t\t]),\n\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\tquery = query.where((eb) =>\n\t\t\t\t\t\teb.or([\n\t\t\t\t\t\t\teb(dbField as any, \">\", orderValue),\n\t\t\t\t\t\t\teb.and([eb(dbField as any, \"=\", orderValue), eb(\"id\", \">\", cursorId)]),\n\t\t\t\t\t\t]),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Apply ordering and limit\n\t\tconst indexedOrderFilter = resolvedOrderField.indexedCustomField\n\t\t\t? resolvedFieldFilters.find((filter) => filter.column === dbField)\n\t\t\t: undefined;\n\t\tif (resolvedOrderField.indexedCustomField && !indexedOrderFilter) {\n\t\t\tquery = query.orderBy(\n\t\t\t\tsql<boolean>`${sql.ref(dbField)} IS NOT NULL`,\n\t\t\t\tsafeOrderDirection === \"ASC\" ? \"asc\" : \"desc\",\n\t\t\t);\n\t\t}\n\t\tif (indexedOrderFilter?.kind !== \"null\") {\n\t\t\tquery = query.orderBy(dbField as any, safeOrderDirection === \"ASC\" ? \"asc\" : \"desc\");\n\t\t}\n\t\tquery = query.orderBy(\"id\", safeOrderDirection === \"ASC\" ? \"asc\" : \"desc\").limit(limit + 1);\n\n\t\t// Run the page fetch and the unbounded count together — the UI needs\n\t\t// both to render a stable denominator (kept on every page intentionally),\n\t\t// and issuing them in parallel on SQLite is essentially free.\n\t\t//\n\t\t// Settled rather than raced: a collection whose table is missing rejects\n\t\t// both, and `Promise.all` returns on the first. The loser stays in flight\n\t\t// holding a pooled connection, so a Postgres pool destroyed in that window\n\t\t// never finishes closing.\n\t\tconst [rowsResult, countResult] = await Promise.allSettled([\n\t\t\tquery.execute(),\n\t\t\tthis.countWithResolvedFilters(type, options.where, resolvedFieldFilters),\n\t\t]);\n\t\tif (rowsResult.status === \"rejected\") throw rowsResult.reason;\n\t\tif (countResult.status === \"rejected\") throw countResult.reason;\n\t\tconst rows = rowsResult.value;\n\t\tconst total = countResult.value;\n\t\tconst hasMore = rows.length > limit;\n\t\tconst items = rows.slice(0, limit);\n\n\t\tconst mappedResult: FindManyResult<ContentItem> = {\n\t\t\titems: items.map((row) => this.mapRow(type, row as Record<string, unknown>)),\n\t\t\ttotal,\n\t\t};\n\n\t\tif (hasMore && items.length > 0) {\n\t\t\tconst lastRow = items.at(-1) as Record<string, unknown>;\n\t\t\tconst lastOrderValue = lastRow[dbField];\n\t\t\tif (resolvedOrderField.indexedCustomField) {\n\t\t\t\tif (\n\t\t\t\t\tlastOrderValue !== null &&\n\t\t\t\t\ttypeof lastOrderValue !== \"string\" &&\n\t\t\t\t\ttypeof lastOrderValue !== \"number\"\n\t\t\t\t) {\n\t\t\t\t\tthrow new EmDashValidationError(`Invalid indexed value for order field: ${orderField}`);\n\t\t\t\t}\n\t\t\t\tmappedResult.nextCursor = encodeIndexedFieldCursor(\n\t\t\t\t\torderField,\n\t\t\t\t\tlastOrderValue,\n\t\t\t\t\tString(lastRow.id),\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tconst orderStr =\n\t\t\t\t\ttypeof lastOrderValue === \"string\" || typeof lastOrderValue === \"number\"\n\t\t\t\t\t\t? String(lastOrderValue)\n\t\t\t\t\t\t: \"\";\n\t\t\t\tmappedResult.nextCursor = encodeCursor(orderStr, String(lastRow.id));\n\t\t\t}\n\t\t}\n\n\t\treturn mappedResult;\n\t}\n\n\t/**\n\t * Update content\n\t */\n\tasync update(type: string, id: string, input: UpdateContentInput): Promise<ContentItem> {\n\t\tconst tableName = getTableName(type);\n\t\tconst now = new Date().toISOString();\n\n\t\t// Every update advances the optimistic-concurrency version. updated_at\n\t\t// advances only when a content-row column actually changes.\n\t\tconst updates: Record<string, unknown> = {};\n\n\t\tif (input.status !== undefined) {\n\t\t\tupdates.status = input.status;\n\t\t}\n\n\t\tif (input.slug !== undefined) {\n\t\t\tupdates.slug = input.slug;\n\t\t}\n\n\t\tif (input.publishedAt !== undefined) {\n\t\t\tupdates.published_at = input.publishedAt;\n\t\t}\n\n\t\tif (input.scheduledAt !== undefined) {\n\t\t\tupdates.scheduled_at = input.scheduledAt;\n\t\t}\n\n\t\tif (input.authorId !== undefined) {\n\t\t\tupdates.author_id = input.authorId;\n\t\t}\n\n\t\tif (input.primaryBylineId !== undefined) {\n\t\t\tupdates.primary_byline_id = input.primaryBylineId;\n\t\t}\n\n\t\t// Update data fields (skip system columns to prevent injection via data)\n\t\tif (input.data !== undefined && typeof input.data === \"object\") {\n\t\t\tfor (const [key, value] of Object.entries(writableContentData(input.data))) {\n\t\t\t\tupdates[key] = serializeValue(value);\n\t\t\t}\n\t\t}\n\n\t\tconst hasColumnWrites = Object.keys(updates).length > 0;\n\t\tif (hasColumnWrites) {\n\t\t\tupdates.updated_at = now;\n\t\t}\n\t\tupdates.version = sql`version + 1`;\n\n\t\tawait this.db\n\t\t\t.updateTable(tableName as keyof Database)\n\t\t\t.set(updates)\n\t\t\t.where(\"id\", \"=\", id)\n\t\t\t.where(\"deleted_at\" as never, \"is\", null)\n\t\t\t.execute();\n\n\t\tif (hasColumnWrites) invalidateCollectionCache(type);\n\n\t\tconst updated = await this.findById(type, id);\n\t\tif (!updated) {\n\t\t\tthrow new Error(\"Content not found\");\n\t\t}\n\n\t\treturn updated;\n\t}\n\n\t/**\n\t * Update plugin-authored fields without letting content columns diverge\n\t * from the revision pointers that publication promotes.\n\t */\n\tasync updateDraftAware(\n\t\ttype: string,\n\t\tid: string,\n\t\tinput: UpdateContentInput,\n\t): Promise<ContentItem> {\n\t\tconst data = input.data ? writableContentData(input.data) : {};\n\t\tconst stagedSlug = typeof input.slug === \"string\" ? input.slug : undefined;\n\t\tconst hasDraftUpdate = Object.keys(data).length > 0 || stagedSlug !== undefined;\n\n\t\tif (!hasDraftUpdate) {\n\t\t\treturn this.update(type, id, { ...input, data });\n\t\t}\n\n\t\tconst collectionRows = await this.db\n\t\t\t.selectFrom(\"_emdash_collections as collection\")\n\t\t\t.leftJoin(\"_emdash_fields as field\", \"field.collection_id\", \"collection.id\")\n\t\t\t.select([\"collection.supports\", \"field.slug as fieldSlug\"])\n\t\t\t.where(\"collection.slug\", \"=\", type)\n\t\t\t.execute();\n\t\tconst supportsRaw = collectionRows[0]?.supports;\n\t\tconst supports: unknown = supportsRaw ? JSON.parse(supportsRaw) : [];\n\t\tif (!Array.isArray(supports) || !supports.includes(\"revisions\")) {\n\t\t\treturn this.update(type, id, { ...input, data });\n\t\t}\n\n\t\tconst fieldSlugs = new Set(collectionRows.map((row) => row.fieldSlug).filter(Boolean));\n\t\tfor (const field of Object.keys(data)) {\n\t\t\tif (!fieldSlugs.has(field)) {\n\t\t\t\tthrow new EmDashValidationError(`Unknown field '${field}' in collection '${type}'`);\n\t\t\t}\n\t\t}\n\n\t\tconst revisionRepo = new RevisionRepository(this.db);\n\t\tlet existing = await this.findById(type, id);\n\n\t\tfor (let attempt = 0; existing && attempt < MAX_DRAFT_STAGE_ATTEMPTS; attempt++) {\n\t\t\tlet baseData = existing.data;\n\t\t\tif (existing.draftRevisionId) {\n\t\t\t\tconst draft = await revisionRepo.findById(existing.draftRevisionId);\n\t\t\t\tif (draft) baseData = draft.data;\n\t\t\t}\n\n\t\t\tconst mergedData = { ...baseData, ...data };\n\t\t\tif (stagedSlug !== undefined) mergedData._slug = stagedSlug;\n\t\t\tconst revision = await revisionRepo.create({\n\t\t\t\tcollection: type,\n\t\t\t\tentryId: id,\n\t\t\t\tdata: mergedData,\n\t\t\t\t...(input.authorId ? { authorId: input.authorId } : {}),\n\t\t\t});\n\n\t\t\tlet staged: boolean;\n\t\t\ttry {\n\t\t\t\tstaged = await this.replaceDraftRevisionForUpdate(type, id, revision.id, existing, input);\n\t\t\t} catch (error) {\n\t\t\t\tawait this.deleteUnstagedRevision(revisionRepo, type, id, revision.id);\n\t\t\t\tthrow error;\n\t\t\t}\n\n\t\t\tif (staged) {\n\t\t\t\tconst updated = await this.findById(type, id);\n\t\t\t\tif (!updated) throw new Error(\"Content not found\");\n\t\t\t\tconst draftData: Record<string, unknown> = {};\n\t\t\t\tfor (const [key, value] of Object.entries(mergedData)) {\n\t\t\t\t\tif (!key.startsWith(\"_\")) draftData[key] = value;\n\t\t\t\t}\n\t\t\t\treturn { ...updated, data: { ...updated.data, ...draftData } };\n\t\t\t}\n\n\t\t\tawait this.deleteUnstagedRevision(revisionRepo, type, id, revision.id);\n\t\t\texisting = await this.findById(type, id);\n\t\t}\n\n\t\tif (!existing) throw new Error(\"Content not found\");\n\t\tthrow new ContentMutationConflictError();\n\t}\n\n\tprivate async deleteUnstagedRevision(\n\t\trevisionRepo: RevisionRepository,\n\t\ttype: string,\n\t\tid: string,\n\t\trevisionId: string,\n\t): Promise<void> {\n\t\ttry {\n\t\t\tawait revisionRepo.deleteIfUnreferenced(type, id, revisionId);\n\t\t} catch (error) {\n\t\t\tconsole.error(`[content] Failed to clean up unstaged revision ${revisionId}:`, error);\n\t\t}\n\t}\n\n\tprivate async replaceDraftRevisionForUpdate(\n\t\ttype: string,\n\t\tid: string,\n\t\trevisionId: string,\n\t\texpected: ContentItem,\n\t\tinput: UpdateContentInput,\n\t): Promise<boolean> {\n\t\tconst tableName = getTableName(type);\n\t\tconst assignments = [sql`draft_revision_id = ${revisionId}`];\n\t\tlet liveMetadataChanged = false;\n\n\t\tif (input.status !== undefined) {\n\t\t\tassignments.push(sql`status = ${input.status}`);\n\t\t\tliveMetadataChanged = true;\n\t\t}\n\t\tif (input.slug === null) {\n\t\t\tassignments.push(sql`slug = NULL`);\n\t\t\tliveMetadataChanged = true;\n\t\t}\n\t\tif (input.publishedAt !== undefined) {\n\t\t\tassignments.push(sql`published_at = ${input.publishedAt}`);\n\t\t\tliveMetadataChanged = true;\n\t\t}\n\t\tif (input.scheduledAt !== undefined) {\n\t\t\tassignments.push(sql`scheduled_at = ${input.scheduledAt}`);\n\t\t\tliveMetadataChanged = true;\n\t\t}\n\t\tif (input.authorId !== undefined) {\n\t\t\tassignments.push(sql`author_id = ${input.authorId}`);\n\t\t\tliveMetadataChanged = true;\n\t\t}\n\t\tif (input.primaryBylineId !== undefined) {\n\t\t\tassignments.push(sql`primary_byline_id = ${input.primaryBylineId}`);\n\t\t\tliveMetadataChanged = true;\n\t\t}\n\t\tif (liveMetadataChanged) assignments.push(sql`updated_at = ${new Date().toISOString()}`);\n\t\tassignments.push(sql`version = version + 1`);\n\n\t\tconst result = await sql`\n\t\t\tUPDATE ${sql.ref(tableName)}\n\t\t\tSET ${sql.join(assignments, sql`, `)}\n\t\t\tWHERE id = ${id}\n\t\t\tAND deleted_at IS NULL\n\t\t\tAND version = ${expected.version}\n\t\t\tAND ${nullableColumnMatch(\"live_revision_id\", expected.liveRevisionId)}\n\t\t\tAND ${nullableColumnMatch(\"draft_revision_id\", expected.draftRevisionId)}\n\t\t\tAND EXISTS (\n\t\t\t\tSELECT 1 FROM revisions\n\t\t\t\tWHERE revisions.id = ${revisionId}\n\t\t\t\tAND revisions.collection = ${type}\n\t\t\t\tAND revisions.entry_id = ${id}\n\t\t\t)\n\t\t`.execute(this.db);\n\n\t\tconst changed = (result.numAffectedRows ?? 0n) > 0n;\n\t\tif (changed && liveMetadataChanged) invalidateCollectionCache(type);\n\t\treturn changed;\n\t}\n\n\t/**\n\t * Delete content (soft delete - moves to trash)\n\t */\n\tasync delete(type: string, id: string): Promise<boolean> {\n\t\tconst tableName = getTableName(type);\n\t\tconst now = new Date().toISOString();\n\n\t\tconst result = await sql`\n\t\t\tUPDATE ${sql.ref(tableName)}\n\t\t\tSET deleted_at = ${now}\n\t\t\tWHERE id = ${id}\n\t\t\tAND deleted_at IS NULL\n\t\t`.execute(this.db);\n\n\t\tconst changed = (result.numAffectedRows ?? 0n) > 0n;\n\t\tif (changed) {\n\t\t\tinvalidateCollectionCache(type);\n\t\t}\n\t\treturn changed;\n\t}\n\n\t/**\n\t * Restore content from trash\n\t */\n\tasync restore(type: string, id: string): Promise<ContentItem | null> {\n\t\tconst tableName = getTableName(type);\n\n\t\tconst result = await sql<Record<string, unknown>>`\n\t\t\tUPDATE ${sql.ref(tableName)}\n\t\t\tSET deleted_at = NULL\n\t\t\tWHERE id = ${id}\n\t\t\tAND deleted_at IS NOT NULL\n\t\t\tRETURNING *\n\t\t`.execute(this.db);\n\n\t\tconst restored = result.rows[0];\n\t\tif (!restored) return null;\n\n\t\tinvalidateCollectionCache(type);\n\t\treturn this.mapRow(type, restored);\n\t}\n\n\t/**\n\t * Permanently delete content (cannot be undone)\n\t */\n\t/**\n\t * Permanently delete a soft-deleted content row.\n\t *\n\t * Returns `true` only when a soft-deleted (trashed) row was removed.\n\t * Returns `false` when no row exists OR when the row exists but is live —\n\t * the caller is responsible for distinguishing these cases (typically via\n\t * a follow-up `findByIdOrSlugIncludingTrashed` to surface NOT_FOUND vs\n\t * NOT_TRASHED). The `AND deleted_at IS NOT NULL` clause is the safety net\n\t * that prevents permanent delete from bypassing the trash workflow.\n\t */\n\tasync permanentDelete(type: string, id: string): Promise<boolean> {\n\t\tconst tableName = getTableName(type);\n\n\t\tconst result = await sql`\n\t\t\tDELETE FROM ${sql.ref(tableName)}\n\t\t\tWHERE id = ${id}\n\t\t\tAND deleted_at IS NOT NULL\n\t\t`.execute(this.db);\n\n\t\tconst changed = (result.numAffectedRows ?? 0n) > 0n;\n\t\tif (changed) invalidateCollectionCache(type);\n\t\treturn changed;\n\t}\n\n\t/**\n\t * Find trashed content items\n\t */\n\tasync findTrashed(\n\t\ttype: string,\n\t\toptions: Omit<FindManyOptions, \"where\"> = {},\n\t): Promise<FindManyResult<ContentItem & { deletedAt: string }>> {\n\t\tconst tableName = getTableName(type);\n\t\tconst limit = Math.min(options.limit || 50, 100);\n\n\t\t// Determine ordering - default to most recently deleted\n\t\tconst orderField = options.orderBy?.field || \"deletedAt\";\n\t\tconst orderDirection = options.orderBy?.direction || \"desc\";\n\t\tconst dbField = this.mapOrderField(orderField);\n\n\t\tconst safeOrderDirection = orderDirection.toLowerCase() === \"asc\" ? \"ASC\" : \"DESC\";\n\n\t\tlet query = this.db\n\t\t\t.selectFrom(tableName as keyof Database)\n\t\t\t.selectAll()\n\t\t\t.where(\"deleted_at\" as never, \"is not\", null);\n\n\t\t// Handle cursor pagination — decodeCursor throws on invalid input.\n\t\tif (options.cursor) {\n\t\t\tconst { orderValue, id: cursorId } = decodeCursor(options.cursor);\n\n\t\t\tif (safeOrderDirection === \"DESC\") {\n\t\t\t\tquery = query.where((eb) =>\n\t\t\t\t\teb.or([\n\t\t\t\t\t\teb(dbField as any, \"<\", orderValue),\n\t\t\t\t\t\teb.and([eb(dbField as any, \"=\", orderValue), eb(\"id\", \"<\", cursorId)]),\n\t\t\t\t\t]),\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tquery = query.where((eb) =>\n\t\t\t\t\teb.or([\n\t\t\t\t\t\teb(dbField as any, \">\", orderValue),\n\t\t\t\t\t\teb.and([eb(dbField as any, \"=\", orderValue), eb(\"id\", \">\", cursorId)]),\n\t\t\t\t\t]),\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tquery = query\n\t\t\t.orderBy(dbField as any, safeOrderDirection === \"ASC\" ? \"asc\" : \"desc\")\n\t\t\t.orderBy(\"id\", safeOrderDirection === \"ASC\" ? \"asc\" : \"desc\")\n\t\t\t.limit(limit + 1);\n\n\t\tconst rows = await query.execute();\n\t\tconst hasMore = rows.length > limit;\n\t\tconst items = rows.slice(0, limit);\n\n\t\tconst mappedResult: FindManyResult<ContentItem & { deletedAt: string }> = {\n\t\t\titems: items.map((row) => {\n\t\t\t\tconst record = row as Record<string, unknown>;\n\t\t\t\treturn {\n\t\t\t\t\t...this.mapRow(type, record),\n\t\t\t\t\tdeletedAt: typeof record.deleted_at === \"string\" ? record.deleted_at : \"\",\n\t\t\t\t};\n\t\t\t}),\n\t\t};\n\n\t\tif (hasMore && items.length > 0) {\n\t\t\tconst lastRow = items.at(-1) as Record<string, unknown>;\n\t\t\tconst lastOrderValue = lastRow[dbField];\n\t\t\tconst orderStr =\n\t\t\t\ttypeof lastOrderValue === \"string\" || typeof lastOrderValue === \"number\"\n\t\t\t\t\t? String(lastOrderValue)\n\t\t\t\t\t: \"\";\n\t\t\tmappedResult.nextCursor = encodeCursor(orderStr, String(lastRow.id));\n\t\t}\n\n\t\treturn mappedResult;\n\t}\n\n\t/**\n\t * Count trashed content items\n\t */\n\tasync countTrashed(type: string): Promise<number> {\n\t\tconst tableName = getTableName(type);\n\n\t\tconst result = await this.db\n\t\t\t.selectFrom(tableName as keyof Database)\n\t\t\t.select((eb) => eb.fn.count(\"id\").as(\"count\"))\n\t\t\t.where(\"deleted_at\" as never, \"is not\", null)\n\t\t\t.executeTakeFirst();\n\n\t\treturn Number(result?.count || 0);\n\t}\n\n\t/**\n\t * Apply the optional `q` filter.\n\t *\n\t * When the handler sets `useFts` (collection has a healthy FTS5 index\n\t * covering the display columns; SQLite only), the filter is served from\n\t * the index: a token-prefix MATCH against `_emdash_fts_<slug>` OR'd with\n\t * an index-served `slug GLOB 'term*'` prefix (the slug is not in the FTS\n\t * index). Both sides are index-backed, so SQLite's OR optimization avoids\n\t * the full-table scan the LIKE fallback needs (#1517). The trade-off is\n\t * search semantics: token-prefix matching instead of arbitrary substring.\n\t *\n\t * Fallback (Postgres, search disabled, or no usable terms): case-\n\t * insensitive substring LIKE across the handler-resolved `searchColumns`\n\t * (OR'd). User input is treated literally (LIKE wildcards escaped) and\n\t * `lower()` is applied on both sides for SQLite/Postgres parity.\n\t */\n\tprivate applySearchFilter<QB extends { where: (cb: (eb: any) => unknown) => QB }>(\n\t\tquery: QB,\n\t\twhere: { q?: string; searchColumns?: string[]; useFts?: boolean } | undefined,\n\t\ttype: string,\n\t): QB {\n\t\tconst term = where?.q?.trim();\n\t\tconst columns = where?.searchColumns;\n\t\tif (!term || !columns || columns.length === 0) return query;\n\n\t\tif (where.useFts) {\n\t\t\tconst match = buildFtsPrefixMatch(term);\n\t\t\tif (match) {\n\t\t\t\tvalidateIdentifier(type, \"collection slug\");\n\t\t\t\tconst ftsTable = `_emdash_fts_${type}`;\n\t\t\t\tconst slugPrefix = buildSlugGlobPrefix(term);\n\t\t\t\treturn query.where((eb) =>\n\t\t\t\t\teb.or([\n\t\t\t\t\t\tsql<boolean>`id IN (SELECT id FROM ${sql.ref(ftsTable)} WHERE ${sql.ref(ftsTable)} MATCH ${match})`,\n\t\t\t\t\t\tsql<boolean>`slug GLOB ${slugPrefix}`,\n\t\t\t\t\t]),\n\t\t\t\t);\n\t\t\t}\n\t\t\t// No usable terms (e.g. quotes only) — fall through to LIKE.\n\t\t}\n\n\t\tconst escaped = term.replace(LIKE_WILDCARD_RE, (c) => `\\\\${c}`);\n\t\tconst pattern = `%${escaped}%`;\n\n\t\treturn query.where((eb) =>\n\t\t\teb.or(\n\t\t\t\tcolumns.map((col) => {\n\t\t\t\t\tvalidateIdentifier(col, \"search column\");\n\t\t\t\t\treturn sql<boolean>`lower(CAST(${sql.ref(col)} AS TEXT)) LIKE lower(${pattern}) ESCAPE '\\\\'`;\n\t\t\t\t}),\n\t\t\t),\n\t\t);\n\t}\n\n\t/**\n\t * Apply the optional inclusive date-range filter. The field is mapped\n\t * through `DATE_FILTER_COLUMNS` (a closed whitelist), and bounds compare\n\t * lexicographically against the stored ISO 8601 timestamps. A `publishedAt`\n\t * range naturally excludes never-published rows (their column is NULL).\n\t */\n\tprivate applyDateFilter<QB extends { where: (cb: (eb: any) => unknown) => QB }>(\n\t\tquery: QB,\n\t\twhere?: { dateFilter?: { field: string; from?: string; to?: string } },\n\t): QB {\n\t\tconst filter = where?.dateFilter;\n\t\tif (!filter) return query;\n\t\tconst column = DATE_FILTER_COLUMNS[filter.field as ContentDateField];\n\t\tif (!column) {\n\t\t\tthrow new EmDashValidationError(`Invalid date filter field: ${filter.field}`);\n\t\t}\n\t\tconst { from, to } = filter;\n\t\tif (!from && !to) return query;\n\n\t\tlet next = query;\n\t\tif (from) next = next.where((eb) => eb(column as any, \">=\", from));\n\t\tif (to) next = next.where((eb) => eb(column as any, \"<=\", to));\n\t\treturn next;\n\t}\n\n\t/**\n\t * Apply the optional byline filter as a correlated (NOT) EXISTS against\n\t * `_emdash_content_bylines`.\n\t *\n\t * Correlating from the content table preserves the outer sort index so\n\t * `LIMIT` can short-circuit. `mode: \"none\"` tests the junction rather than\n\t * `primary_byline_id` because the two are written in the same call but\n\t * are not atomically consistent, so the junction is authoritative.\n\t *\n\t * Whether a credit *renders* is locale-scoped; whether one *exists* is\n\t * not. Both are needed: the first decides what the filter matches, the\n\t * second decides whether the author fallback applies at all.\n\t */\n\tprivate applyBylineFilter<QB extends { where: (cb: (eb: any) => unknown) => QB }>(\n\t\tquery: QB,\n\t\twhere: { bylineFilter?: ContentBylineFilter } | undefined,\n\t\ttype: string,\n\t): QB {\n\t\tconst filter = where?.bylineFilter;\n\t\tif (!filter) return query;\n\t\tconst tableName = getTableName(type);\n\t\tconst idColumn = `${tableName}.id`;\n\t\tconst authorColumn = `${tableName}.author_id`;\n\t\tconst localeColumn = `${tableName}.locale`;\n\n\t\t// An explicit credit that actually renders — optionally within a given\n\t\t// set of translation groups. The junction stores a group, but a credit\n\t\t// resolves only where that group has a byline row at the locale the\n\t\t// list is scoped to, so this repeats the join `getContentBylinesMany`\n\t\t// makes. `locale` falls back to each entry's own when the list spans\n\t\t// locales.\n\t\tconst creditRenders = (eb: any, bylineIds?: string[]) => {\n\t\t\tlet sub = eb\n\t\t\t\t.selectFrom(\"_emdash_content_bylines as cb\")\n\t\t\t\t.innerJoin(\"_emdash_bylines as b\", \"b.translation_group\", \"cb.byline_id\")\n\t\t\t\t.select(\"cb.id\")\n\t\t\t\t.where(\"cb.collection_slug\", \"=\", type)\n\t\t\t\t.whereRef(\"cb.content_id\", \"=\", idColumn);\n\t\t\tsub = filter.locale\n\t\t\t\t? sub.where(\"b.locale\", \"=\", filter.locale)\n\t\t\t\t: sub.whereRef(\"b.locale\", \"=\", localeColumn);\n\t\t\tif (bylineIds) sub = sub.where(\"cb.byline_id\", \"in\", bylineIds);\n\t\t\treturn eb.exists(sub);\n\t\t};\n\n\t\t// Whether the entry carries an explicit credit at all, at any locale.\n\t\t// Deliberately not locale-scoped: the author fallback is suppressed by\n\t\t// the presence of a junction row, even one that renders nothing here\n\t\t// (`hydrateBylinesMany` gates inference on `primaryBylineId`).\n\t\tconst hasExplicitCredit = (eb: any) =>\n\t\t\teb.exists(\n\t\t\t\teb\n\t\t\t\t\t.selectFrom(\"_emdash_content_bylines as cb\")\n\t\t\t\t\t.select(\"cb.id\")\n\t\t\t\t\t.where(\"cb.collection_slug\", \"=\", type)\n\t\t\t\t\t.whereRef(\"cb.content_id\", \"=\", idColumn),\n\t\t\t);\n\n\t\t// The entry's author owns a byline row — optionally within a given set\n\t\t// of translation groups — at the locale the list is scoped to. Matching\n\t\t// the locale is what keeps the filter agreeing with the list: an\n\t\t// inferred credit renders only when the author's byline has a row at\n\t\t// that locale (`hydrateBylinesMany` -> `findByUserIds`), and byline\n\t\t// translations start life with a null `user_id`, so a group translated\n\t\t// into the locale but not re-linked resolves to no credit. `locale`\n\t\t// falls back to each entry's own when the list spans locales.\n\t\tconst authorHasByline = (eb: any, bylineIds?: string[]) => {\n\t\t\tlet sub = eb\n\t\t\t\t.selectFrom(\"_emdash_bylines as b\")\n\t\t\t\t.select(\"b.id\")\n\t\t\t\t.whereRef(\"b.user_id\", \"=\", authorColumn);\n\t\t\tsub = filter.locale\n\t\t\t\t? sub.where(\"b.locale\", \"=\", filter.locale)\n\t\t\t\t: sub.whereRef(\"b.locale\", \"=\", localeColumn);\n\t\t\tif (bylineIds) sub = sub.where(\"b.translation_group\", \"in\", bylineIds);\n\t\t\treturn eb.exists(sub);\n\t\t};\n\n\t\tif (filter.mode === \"none\") {\n\t\t\treturn query.where((eb: any) => {\n\t\t\t\tconst uncredited = eb.not(creditRenders(eb));\n\t\t\t\t// With inference on, \"no byline\" means none is rendered, so an\n\t\t\t\t// entry that falls through to an author byline is excluded too.\n\t\t\t\treturn filter.includeInferred\n\t\t\t\t\t? eb.and([uncredited, eb.or([hasExplicitCredit(eb), eb.not(authorHasByline(eb))])])\n\t\t\t\t\t: uncredited;\n\t\t\t});\n\t\t}\n\n\t\tconst bylineIds = filter.bylineIds ?? [];\n\t\tif (bylineIds.length === 0) {\n\t\t\t// A filter that resolved to no ids must match nothing rather than\n\t\t\t// silently degrade to \"no filter\" and return the whole collection.\n\t\t\t// `1 = 0` rather than a bound `false`: better-sqlite3 refuses to\n\t\t\t// bind JS booleans.\n\t\t\treturn query.where(() => sql<boolean>`1 = 0`);\n\t\t}\n\n\t\treturn query.where((eb: any) => {\n\t\t\tif (!filter.includeInferred) return creditRenders(eb, bylineIds);\n\t\t\t// Inference applies only where no explicit credit exists, so an\n\t\t\t// entry credited to someone else never matches on its author.\n\t\t\treturn eb.or([\n\t\t\t\tcreditRenders(eb, bylineIds),\n\t\t\t\teb.and([eb.not(hasExplicitCredit(eb)), authorHasByline(eb, bylineIds)]),\n\t\t\t]);\n\t\t});\n\t}\n\n\t/**\n\t * Count content items\n\t */\n\tasync count(type: string, where?: FindManyOptions[\"where\"]): Promise<number> {\n\t\tconst resolvedFieldFilters = await this.resolveFieldFilters(type, where?.fieldFilters);\n\t\treturn this.countWithResolvedFilters(type, where, resolvedFieldFilters);\n\t}\n\n\tprivate async countWithResolvedFilters(\n\t\ttype: string,\n\t\twhere: FindManyOptions[\"where\"] | undefined,\n\t\tresolvedFieldFilters: ResolvedFieldFilter[],\n\t): Promise<number> {\n\t\tconst tableName = getTableName(type);\n\n\t\tlet query = this.db\n\t\t\t.selectFrom(tableName as keyof Database)\n\t\t\t.select((eb) => eb.fn.count(\"id\").as(\"count\"))\n\t\t\t.where(\"deleted_at\" as never, \"is\", null);\n\n\t\tif (where?.status) {\n\t\t\tquery = query.where(\"status\", \"=\", where.status);\n\t\t}\n\n\t\tif (where?.authorId) {\n\t\t\tquery = query.where(\"author_id\", \"=\", where.authorId);\n\t\t}\n\n\t\tif (where?.locale) {\n\t\t\tquery = query.where(\"locale\" as any, \"=\", where.locale);\n\t\t}\n\n\t\tquery = this.applySearchFilter(query, where, type);\n\t\tquery = this.applyDateFilter(query, where);\n\t\tquery = this.applyBylineFilter(query, where, type);\n\t\tquery = this.applyFieldFilters(query, resolvedFieldFilters);\n\n\t\tconst result = await query.executeTakeFirst();\n\t\treturn Number(result?.count || 0);\n\t}\n\n\t/**\n\t * Distinct, non-null `author_id` values across the collection's live\n\t * (non-trashed) content. Used to populate the admin author filter with\n\t * only the users who have actually authored entries, rather than the\n\t * full user directory (which requires admin privileges to read).\n\t */\n\tasync findDistinctAuthorIds(type: string): Promise<string[]> {\n\t\tconst tableName = getTableName(type);\n\n\t\tconst rows = await this.db\n\t\t\t.selectFrom(tableName as keyof Database)\n\t\t\t.select(\"author_id\")\n\t\t\t.distinct()\n\t\t\t.where(\"deleted_at\" as never, \"is\", null)\n\t\t\t.where(\"author_id\" as never, \"is not\", null)\n\t\t\t.execute();\n\n\t\treturn rows.map((row) => row.author_id).filter((id): id is string => id !== null);\n\t}\n\n\t// get overall statistics for a content type in a single query\n\tasync getStats(\n\t\ttype: string,\n\t\tnow = new Date(),\n\t): Promise<{\n\t\ttotal: number;\n\t\tpublished: number;\n\t\tdraft: number;\n\t\tscheduled: number;\n\t\toverdueScheduled: number;\n\t}> {\n\t\tconst tableName = getTableName(type);\n\t\tconst nowIso = now.toISOString();\n\n\t\tconst result = await this.db\n\t\t\t.selectFrom(tableName as keyof Database)\n\t\t\t.select((eb) => [\n\t\t\t\teb.fn.count(\"id\").as(\"total\"),\n\t\t\t\teb.fn.sum(eb.case().when(\"status\", \"=\", \"published\").then(1).else(0).end()).as(\"published\"),\n\t\t\t\teb.fn.sum(eb.case().when(\"status\", \"=\", \"draft\").then(1).else(0).end()).as(\"draft\"),\n\t\t\t\tsql<number>`SUM(CASE WHEN scheduled_at IS NOT NULL THEN 1 ELSE 0 END)`.as(\"scheduled\"),\n\t\t\t\tsql<number>`SUM(CASE WHEN scheduled_at IS NOT NULL AND scheduled_at <= ${nowIso} THEN 1 ELSE 0 END)`.as(\n\t\t\t\t\t\"overdue_scheduled\",\n\t\t\t\t),\n\t\t\t])\n\t\t\t.where(\"deleted_at\" as never, \"is\", null)\n\t\t\t.executeTakeFirst();\n\n\t\treturn {\n\t\t\ttotal: Number(result?.total || 0),\n\t\t\tpublished: Number(result?.published || 0),\n\t\t\tdraft: Number(result?.draft || 0),\n\t\t\tscheduled: Number(result?.scheduled || 0),\n\t\t\toverdueScheduled: Number(result?.overdue_scheduled || 0),\n\t\t};\n\t}\n\n\t/**\n\t * Schedule content for future publishing\n\t *\n\t * Sets status to 'scheduled' and stores the scheduled publish time.\n\t * The content will be auto-published when the scheduled time is reached.\n\t */\n\tasync schedule(type: string, id: string, scheduledAt: string): Promise<ContentItem> {\n\t\tconst tableName = getTableName(type);\n\t\tconst now = new Date().toISOString();\n\n\t\t// Validate scheduledAt is in the future\n\t\tconst scheduledDate = new Date(scheduledAt);\n\t\tif (isNaN(scheduledDate.getTime())) {\n\t\t\tthrow new EmDashValidationError(\"Invalid scheduled date\");\n\t\t}\n\t\tif (scheduledDate <= new Date()) {\n\t\t\tthrow new EmDashValidationError(\"Scheduled date must be in the future\");\n\t\t}\n\n\t\tconst existing = await this.findById(type, id);\n\t\tif (!existing) {\n\t\t\tthrow new EmDashValidationError(\"Content item not found\");\n\t\t}\n\n\t\t// Published posts keep their status — the schedule applies to the\n\t\t// pending draft, not the currently-live revision. Unpublished posts\n\t\t// transition to 'scheduled' so they aren't visible before the time.\n\t\tconst newStatus = existing.status === \"published\" ? \"published\" : \"scheduled\";\n\n\t\tawait sql`\n\t\t\tUPDATE ${sql.ref(tableName)}\n\t\t\tSET status = ${newStatus},\n\t\t\t\tscheduled_at = ${scheduledAt},\n\t\t\t\tupdated_at = ${now}\n\t\t\tWHERE id = ${id}\n\t\t\tAND deleted_at IS NULL\n\t\t`.execute(this.db);\n\n\t\tinvalidateCollectionCache(type);\n\n\t\tconst updated = await this.findById(type, id);\n\t\tif (!updated) {\n\t\t\tthrow new Error(\"Content not found\");\n\t\t}\n\n\t\treturn updated;\n\t}\n\n\t/**\n\t * Unschedule content\n\t *\n\t * Clears the scheduled time. Published posts stay published;\n\t * draft/scheduled posts revert to 'draft'.\n\t */\n\tasync unschedule(type: string, id: string): Promise<ContentItem> {\n\t\tconst tableName = getTableName(type);\n\t\tconst now = new Date().toISOString();\n\n\t\tconst existing = await this.findById(type, id);\n\t\tif (!existing) {\n\t\t\tthrow new EmDashValidationError(\"Content item not found\");\n\t\t}\n\n\t\t// Published posts keep their status — just clear the pending schedule.\n\t\t// Draft/scheduled posts revert to 'draft'.\n\t\tconst newStatus = existing.status === \"published\" ? \"published\" : \"draft\";\n\n\t\tawait sql`\n\t\t\tUPDATE ${sql.ref(tableName)}\n\t\t\tSET status = ${newStatus},\n\t\t\t\tscheduled_at = NULL,\n\t\t\t\tupdated_at = ${now}\n\t\t\tWHERE id = ${id}\n\t\t\tAND scheduled_at IS NOT NULL\n\t\t\tAND deleted_at IS NULL\n\t\t`.execute(this.db);\n\n\t\tinvalidateCollectionCache(type);\n\n\t\tconst updated = await this.findById(type, id);\n\t\tif (!updated) {\n\t\t\tthrow new Error(\"Content not found\");\n\t\t}\n\n\t\treturn updated;\n\t}\n\n\t/**\n\t * Find content that is ready to be published\n\t *\n\t * Returns all content where scheduled_at <= now, regardless of status.\n\t * This covers both draft-scheduled posts (status='scheduled') and\n\t * published posts with scheduled draft changes (status='published').\n\t *\n\t * `limit` (optional) caps how many due rows are returned, oldest-due first.\n\t * The scheduled-publishing sweep passes a limit so a large backlog can't\n\t * fan out unbounded publish/webhook work in a single tick (and blow a Worker\n\t * invocation's CPU/subrequest budget); the remainder drains on later ticks.\n\t */\n\tasync findReadyToPublish(type: string, limit?: number): Promise<ContentItem[]> {\n\t\tconst tableName = getTableName(type);\n\t\tconst now = new Date().toISOString();\n\n\t\t// Embed an empty fragment when unbounded so callers that want every due\n\t\t// row (manual flows, tests) keep the original behaviour.\n\t\tconst limitClause =\n\t\t\ttypeof limit === \"number\" && Number.isInteger(limit) && limit > 0\n\t\t\t\t? sql`LIMIT ${limit}`\n\t\t\t\t: sql``;\n\n\t\tconst result = await sql<Record<string, unknown>>`\n\t\t\tSELECT * FROM ${sql.ref(tableName)}\n\t\t\tWHERE scheduled_at IS NOT NULL\n\t\t\tAND scheduled_at <= ${now}\n\t\t\tAND deleted_at IS NULL\n\t\t\tORDER BY scheduled_at ASC\n\t\t\t${limitClause}\n\t\t`.execute(this.db);\n\n\t\treturn result.rows.map((row) => this.mapRow(type, row));\n\t}\n\n\t/**\n\t * Find all translations in a translation group\n\t */\n\tasync findTranslations(type: string, translationGroup: string): Promise<ContentItem[]> {\n\t\tconst tableName = getTableName(type);\n\n\t\tconst result = await sql<Record<string, unknown>>`\n\t\t\tSELECT * FROM ${sql.ref(tableName)}\n\t\t\tWHERE translation_group = ${translationGroup}\n\t\t\tAND deleted_at IS NULL\n\t\t\tORDER BY locale ASC\n\t\t`.execute(this.db);\n\n\t\treturn result.rows.map((row) => this.mapRow(type, row));\n\t}\n\n\t/**\n\t * Batch variant of {@link findTranslations}: every (non-deleted) locale\n\t * variant for any of `translationGroups`, in one `WHERE translation_group IN\n\t * (...)` query chunked at `SQL_BATCH_SIZE` for D1's bind-parameter limit.\n\t * Lets callers resolve many edge groups without an N+1 per group. The caller\n\t * groups the flat result by `translationGroup` itself.\n\t *\n\t * `translation_group` leads the sort so the ordering follows\n\t * `idx_{table}_del_tg_locale` past its `deleted_at` equality; callers group by\n\t * `translationGroup`, so the per-group locale order they rely on is preserved.\n\t *\n\t * `publishedOnly` restricts the result to `status = 'published'` — reference\n\t * reads pass this for callers without `content:read_drafts` so draft/scheduled\n\t * entries never leak through an edge traversal.\n\t *\n\t * A reference edge stores only a collection slug (no SQL FK), so the table may\n\t * have been dropped since the edge was written. That is a tolerated dangling\n\t * state, not an error: a missing table resolves to no rows, mirroring how the\n\t * content read handlers treat `isMissingTableError`.\n\t */\n\tasync findTranslationsForGroups(\n\t\ttype: string,\n\t\ttranslationGroups: string[],\n\t\toptions: { publishedOnly?: boolean } = {},\n\t): Promise<ContentItem[]> {\n\t\tif (translationGroups.length === 0) return [];\n\t\tconst tableName = getTableName(type);\n\t\tconst publishedFilter = options.publishedOnly ? sql`AND status = 'published'` : sql``;\n\n\t\tconst items: ContentItem[] = [];\n\t\ttry {\n\t\t\tfor (const chunk of chunks(translationGroups, SQL_BATCH_SIZE)) {\n\t\t\t\tconst result = await sql<Record<string, unknown>>`\n\t\t\t\t\tSELECT * FROM ${sql.ref(tableName)}\n\t\t\t\t\tWHERE translation_group IN (${sql.join(chunk)})\n\t\t\t\t\tAND deleted_at IS NULL\n\t\t\t\t\t${publishedFilter}\n\t\t\t\t\tORDER BY translation_group ASC, locale ASC\n\t\t\t\t`.execute(this.db);\n\t\t\t\tfor (const row of result.rows) items.push(this.mapRow(type, row));\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif (isMissingTableError(error)) return [];\n\t\t\tthrow error;\n\t\t}\n\t\treturn items;\n\t}\n\n\t/**\n\t * Batch variant of {@link findByIdOrSlug}: resolve many identifiers (each an\n\t * id OR a slug) within `type` in a constant number of queries — one `WHERE id\n\t * IN (...)` and one `WHERE slug IN (...)`, each chunked at `SQL_BATCH_SIZE`.\n\t * Returns a map from the input identifier to its resolved item; identifiers\n\t * that match nothing are absent. Used on write paths that accept a list of\n\t * references, so a single request doesn't fan out to an N+1 of point lookups.\n\t *\n\t * Resolution mirrors {@link findByIdOrSlug}: a ULID-shaped identifier prefers\n\t * the id match and falls back to slug; anything else prefers the slug match\n\t * and falls back to id. Slug matches collapse to the lowest-locale variant\n\t * (`ORDER BY locale ASC`), matching the slug-without-locale lookup.\n\t */\n\tasync findManyByIdOrSlug(type: string, identifiers: string[]): Promise<Map<string, ContentItem>> {\n\t\tconst resolved = new Map<string, ContentItem>();\n\t\tconst unique = [...new Set(identifiers)];\n\t\tif (unique.length === 0) return resolved;\n\n\t\tconst tableName = getTableName(type);\n\t\tconst byId = new Map<string, ContentItem>();\n\t\tconst bySlug = new Map<string, ContentItem>();\n\n\t\ttry {\n\t\t\tfor (const chunk of chunks(unique, SQL_BATCH_SIZE)) {\n\t\t\t\tconst idRows = await sql<Record<string, unknown>>`\n\t\t\t\t\tSELECT * FROM ${sql.ref(tableName)}\n\t\t\t\t\tWHERE id IN (${sql.join(chunk)})\n\t\t\t\t\tAND deleted_at IS NULL\n\t\t\t\t`.execute(this.db);\n\t\t\t\tfor (const row of idRows.rows) {\n\t\t\t\t\tconst item = this.mapRow(type, row);\n\t\t\t\t\tbyId.set(item.id, item);\n\t\t\t\t}\n\n\t\t\t\tconst slugRows = await sql<Record<string, unknown>>`\n\t\t\t\t\tSELECT * FROM ${sql.ref(tableName)}\n\t\t\t\t\tWHERE slug IN (${sql.join(chunk)})\n\t\t\t\t\tAND deleted_at IS NULL\n\t\t\t\t\tORDER BY locale ASC\n\t\t\t\t`.execute(this.db);\n\t\t\t\tfor (const row of slugRows.rows) {\n\t\t\t\t\tconst item = this.mapRow(type, row);\n\t\t\t\t\t// First write wins → lowest locale, matching findBySlug without a locale.\n\t\t\t\t\tif (item.slug != null && !bySlug.has(item.slug)) bySlug.set(item.slug, item);\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (error) {\n\t\t\t// A collection dropped after a relation was created leaves the relation\n\t\t\t// pointing at a missing table. Treat it like an empty collection (no\n\t\t\t// matches) so callers surface a structured NOT_FOUND, not a 500 —\n\t\t\t// mirroring findTranslationsForGroups.\n\t\t\tif (isMissingTableError(error)) return resolved;\n\t\t\tthrow error;\n\t\t}\n\n\t\tfor (const identifier of unique) {\n\t\t\tconst looksLikeUlid = ULID_PATTERN.test(identifier);\n\t\t\tconst item = looksLikeUlid\n\t\t\t\t? (byId.get(identifier) ?? bySlug.get(identifier))\n\t\t\t\t: (bySlug.get(identifier) ?? byId.get(identifier));\n\t\t\tif (item) resolved.set(identifier, item);\n\t\t}\n\t\treturn resolved;\n\t}\n\n\t/**\n\t * Publish the current draft\n\t *\n\t * Promotes draft_revision_id to live_revision_id and clears draft pointer.\n\t * Syncs the draft revision's data into the content table columns so the\n\t * content table always reflects the published version.\n\t * If no draft revision exists, creates one from current data and publishes it.\n\t * When `promoteRevision` is false, publishes the current content-table data\n\t * by changing lifecycle metadata only.\n\t *\n\t * `publishedAt` (optional) overrides the publication timestamp. If omitted,\n\t * the existing `published_at` is preserved (idempotent re-publish keeps the\n\t * original date) and falls back to the current time on first publish. Pass\n\t * an explicit value to backdate a publish (e.g. when migrating content from\n\t * another CMS).\n\t *\n\t * `requireDue` gates the final update on the row still being due.\n\t * `expectedScheduledAt` additionally fences changes made after a sweep\n\t * selected the row but before publication preparation began.\n\t */\n\tasync publish(\n\t\ttype: string,\n\t\tid: string,\n\t\tpublishedAt?: string,\n\t\trequireDue = false,\n\t\texpectedScheduledAt?: string,\n\t\tpromoteRevision = true,\n\t\trequireSlug = true,\n\t): Promise<ContentItem> {\n\t\tconst tableName = getTableName(type);\n\t\tconst now = new Date().toISOString();\n\n\t\tconst existing = await this.findById(type, id);\n\t\tif (!existing) {\n\t\t\tthrow new EmDashValidationError(\"Content item not found\");\n\t\t}\n\t\tif (\n\t\t\trequireDue &&\n\t\t\texpectedScheduledAt !== undefined &&\n\t\t\texisting.scheduledAt !== expectedScheduledAt\n\t\t) {\n\t\t\tthrow new ScheduledNotDueError();\n\t\t}\n\t\tif (!promoteRevision && requireSlug && !existing.slug?.trim()) {\n\t\t\tthrow new EmDashValidationError(\"Cannot publish routable content without a slug\");\n\t\t}\n\n\t\tif (!promoteRevision) {\n\t\t\tconst revisionRepo = new RevisionRepository(this.db);\n\t\t\tlet provisionalRevisionId: string | null = null;\n\t\t\ttry {\n\t\t\t\tlet liveRevisionId = existing.liveRevisionId;\n\t\t\t\tif (!liveRevisionId) {\n\t\t\t\t\tconst revision = await revisionRepo.create({\n\t\t\t\t\t\tcollection: type,\n\t\t\t\t\t\tentryId: id,\n\t\t\t\t\t\tdata: existing.data,\n\t\t\t\t\t});\n\t\t\t\t\tliveRevisionId = revision.id;\n\t\t\t\t\tprovisionalRevisionId = revision.id;\n\t\t\t\t}\n\n\t\t\t\tconst intendedPublishedAt = publishedAt ?? existing.publishedAt ?? now;\n\t\t\t\tconst duePredicate = requireDue\n\t\t\t\t\t? sql`AND scheduled_at IS NOT NULL AND scheduled_at <= ${now}`\n\t\t\t\t\t: sql``;\n\t\t\t\tlet published = false;\n\t\t\t\ttry {\n\t\t\t\t\tconst result = await sql`\n\t\t\t\t\t\tUPDATE ${sql.ref(tableName)}\n\t\t\t\t\t\tSET live_revision_id = ${liveRevisionId},\n\t\t\t\t\t\t\tdraft_revision_id = NULL,\n\t\t\t\t\t\t\tstatus = 'published',\n\t\t\t\t\t\t\tscheduled_at = NULL,\n\t\t\t\t\t\t\tpublished_at = ${intendedPublishedAt},\n\t\t\t\t\t\t\tupdated_at = ${now},\n\t\t\t\t\t\t\tversion = version + 1\n\t\t\t\t\t\tWHERE id = ${id}\n\t\t\t\t\t\tAND deleted_at IS NULL\n\t\t\t\t\t\tAND version = ${existing.version}\n\t\t\t\t\t\tAND status = ${existing.status}\n\t\t\t\t\t\tAND ${nullableColumnMatch(\"live_revision_id\", existing.liveRevisionId)}\n\t\t\t\t\t\tAND ${nullableColumnMatch(\"draft_revision_id\", existing.draftRevisionId)}\n\t\t\t\t\t\tAND ${nullableColumnMatch(\"scheduled_at\", existing.scheduledAt)}\n\t\t\t\t\t\t${duePredicate}\n\t\t\t\t\t`.execute(this.db);\n\t\t\t\t\tpublished = (result.numAffectedRows ?? 0n) > 0n;\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (isConfirmedStatementFailure(error)) throw error;\n\t\t\t\t\tlet observed: ContentItem | null;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tobserved = await this.findById(type, id);\n\t\t\t\t\t} catch (reconciliationError) {\n\t\t\t\t\t\tthrow new Error(\"Unable to confirm whether content publication completed\", {\n\t\t\t\t\t\t\tcause: reconciliationError,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tif (!observed) {\n\t\t\t\t\t\tthrow new Error(\"Unable to confirm whether content publication completed\", {\n\t\t\t\t\t\t\tcause: error,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tpublished = matchesLifecyclePublication(\n\t\t\t\t\t\tobserved,\n\t\t\t\t\t\texisting,\n\t\t\t\t\t\tliveRevisionId,\n\t\t\t\t\t\tintendedPublishedAt,\n\t\t\t\t\t\tnow,\n\t\t\t\t\t);\n\t\t\t\t\tif (!published && matchesPublicationFence(observed, existing)) throw error;\n\t\t\t\t\tif (!published) {\n\t\t\t\t\t\tthrow new Error(\"Unable to confirm whether content publication completed\", {\n\t\t\t\t\t\t\tcause: error,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (!published) {\n\t\t\t\t\tthrow requireDue ? new ScheduledNotDueError() : new ContentMutationConflictError();\n\t\t\t\t}\n\n\t\t\t\tinvalidateCollectionCache(type);\n\t\t\t\tconst updated = await this.findById(type, id);\n\t\t\t\tif (!updated) throw new Error(\"Content not found\");\n\t\t\t\treturn updated;\n\t\t\t} catch (error) {\n\t\t\t\tif (provisionalRevisionId) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait revisionRepo.deleteIfUnreferenced(type, id, provisionalRevisionId);\n\t\t\t\t\t} catch (cleanupError) {\n\t\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t\t`[content] Failed to clean up provisional revision ${provisionalRevisionId}:`,\n\t\t\t\t\t\t\tcleanupError,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\n\t\tconst revisionRepo = new RevisionRepository(this.db);\n\t\tlet provisionalRevisionId: string | null = null;\n\t\ttry {\n\t\t\tlet revisionToPublish = existing.draftRevisionId || existing.liveRevisionId;\n\n\t\t\tif (!revisionToPublish) {\n\t\t\t\tconst revision = await revisionRepo.create({\n\t\t\t\t\tcollection: type,\n\t\t\t\t\tentryId: id,\n\t\t\t\t\tdata: existing.data,\n\t\t\t\t});\n\t\t\t\trevisionToPublish = revision.id;\n\t\t\t\tprovisionalRevisionId = revision.id;\n\t\t\t}\n\n\t\t\tconst revision = await revisionRepo.findById(revisionToPublish);\n\t\t\tif (!revision || revision.collection !== type || revision.entryId !== id) {\n\t\t\t\tthrow new EmDashValidationError(\"Revision does not belong to the specified content item\");\n\t\t\t}\n\n\t\t\tconst stagedSlug = typeof revision.data._slug === \"string\" ? revision.data._slug : null;\n\t\t\tconst intendedSlug = stagedSlug ?? existing.slug;\n\t\t\tif (requireSlug && !intendedSlug?.trim()) {\n\t\t\t\tthrow new EmDashValidationError(\"Cannot publish routable content without a slug\");\n\t\t\t}\n\t\t\tconst intendedPublishedAt = publishedAt ?? existing.publishedAt ?? now;\n\t\t\tif (stagedSlug !== null && stagedSlug !== existing.slug && existing.locale !== null) {\n\t\t\t\tconst conflict = await this.findBySlugIncludingTrashed(type, stagedSlug, existing.locale);\n\t\t\t\tif (conflict && conflict.id !== id) {\n\t\t\t\t\tthrow new EmDashValidationError(\n\t\t\t\t\t\t`Cannot publish: slug '${stagedSlug}' is already used by another entry` +\n\t\t\t\t\t\t\t` in this collection (id: ${conflict.id}). Choose a different slug.`,\n\t\t\t\t\t\t{ code: \"SLUG_CONFLICT\" },\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst assignments: ReturnType<typeof sql>[] = [];\n\t\t\tif (stagedSlug !== null) assignments.push(sql`slug = ${stagedSlug}`);\n\t\t\tfor (const [key, value] of Object.entries(revision.data)) {\n\t\t\t\tif (SYSTEM_COLUMNS.has(key) || key.startsWith(\"_\")) continue;\n\t\t\t\tvalidateIdentifier(key, \"content field name\");\n\t\t\t\tassignments.push(sql`${sql.ref(key)} = ${serializeValue(value)}`);\n\t\t\t}\n\t\t\tassignments.push(\n\t\t\t\tsql`live_revision_id = ${revisionToPublish}`,\n\t\t\t\tsql`draft_revision_id = NULL`,\n\t\t\t\tsql`status = 'published'`,\n\t\t\t\tsql`scheduled_at = NULL`,\n\t\t\t\tsql`published_at = ${intendedPublishedAt}`,\n\t\t\t\tsql`updated_at = ${now}`,\n\t\t\t\tsql`version = version + 1`,\n\t\t\t);\n\n\t\t\tconst duePredicate = requireDue\n\t\t\t\t? sql`AND scheduled_at IS NOT NULL AND scheduled_at <= ${now}`\n\t\t\t\t: sql``;\n\t\t\tlet promoted = false;\n\t\t\ttry {\n\t\t\t\tconst result = await sql`\n\t\t\t\t\tUPDATE ${sql.ref(tableName)}\n\t\t\t\t\tSET ${sql.join(assignments, sql`, `)}\n\t\t\t\t\tWHERE id = ${id}\n\t\t\t\t\tAND deleted_at IS NULL\n\t\t\t\t\tAND version = ${existing.version}\n\t\t\t\t\tAND status = ${existing.status}\n\t\t\t\t\tAND ${nullableColumnMatch(\"live_revision_id\", existing.liveRevisionId)}\n\t\t\t\t\tAND ${nullableColumnMatch(\"draft_revision_id\", existing.draftRevisionId)}\n\t\t\t\t\tAND ${nullableColumnMatch(\"scheduled_at\", existing.scheduledAt)}\n\t\t\t\t\t${duePredicate}\n\t\t\t\t\tAND EXISTS (\n\t\t\t\t\t\tSELECT 1 FROM revisions\n\t\t\t\t\t\tWHERE revisions.id = ${revisionToPublish}\n\t\t\t\t\t\tAND revisions.collection = ${type}\n\t\t\t\t\t\tAND revisions.entry_id = ${id}\n\t\t\t\t\t)\n\t\t\t\t`.execute(this.db);\n\t\t\t\tpromoted = (result.numAffectedRows ?? 0n) > 0n;\n\t\t\t} catch (error) {\n\t\t\t\tif (isConfirmedStatementFailure(error)) throw error;\n\t\t\t\tlet observed: ContentItem | null;\n\t\t\t\ttry {\n\t\t\t\t\tobserved = await this.findById(type, id);\n\t\t\t\t} catch (reconciliationError) {\n\t\t\t\t\tthrow new Error(\"Unable to confirm whether content publication completed\", {\n\t\t\t\t\t\tcause: reconciliationError,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tif (!observed) {\n\t\t\t\t\tthrow new Error(\"Unable to confirm whether content publication completed\", {\n\t\t\t\t\t\tcause: error,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tpromoted = matchesPublication(\n\t\t\t\t\tobserved,\n\t\t\t\t\texisting,\n\t\t\t\t\trevision,\n\t\t\t\t\trevisionToPublish,\n\t\t\t\t\tintendedSlug,\n\t\t\t\t\tintendedPublishedAt,\n\t\t\t\t\tnow,\n\t\t\t\t);\n\t\t\t\tif (!promoted && matchesPublicationFence(observed, existing)) throw error;\n\t\t\t\tif (!promoted) {\n\t\t\t\t\tthrow new Error(\"Unable to confirm whether content publication completed\", {\n\t\t\t\t\t\tcause: error,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!promoted) {\n\t\t\t\tthrow requireDue ? new ScheduledNotDueError() : new ContentMutationConflictError();\n\t\t\t}\n\n\t\t\tinvalidateCollectionCache(type);\n\t\t\tconst updated = await this.findById(type, id);\n\t\t\tif (!updated) {\n\t\t\t\tthrow new Error(\"Content not found\");\n\t\t\t}\n\n\t\t\treturn updated;\n\t\t} catch (error) {\n\t\t\tif (provisionalRevisionId) {\n\t\t\t\ttry {\n\t\t\t\t\tawait revisionRepo.deleteIfUnreferenced(type, id, provisionalRevisionId);\n\t\t\t\t} catch (cleanupError) {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t`[content] Failed to clean up provisional revision ${provisionalRevisionId}:`,\n\t\t\t\t\t\tcleanupError,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/**\n\t * Unpublish content\n\t *\n\t * Removes live pointer but preserves draft. If no draft exists,\n\t * creates one from the live version so the content isn't lost.\n\t */\n\tasync unpublish(type: string, id: string): Promise<ContentItem> {\n\t\tconst tableName = getTableName(type);\n\t\tconst now = new Date().toISOString();\n\n\t\tconst existing = await this.findById(type, id);\n\t\tif (!existing) {\n\t\t\tthrow new EmDashValidationError(\"Content item not found\");\n\t\t}\n\n\t\t// If no draft exists, create one from the live version\n\t\tif (!existing.draftRevisionId && existing.liveRevisionId) {\n\t\t\tconst revisionRepo = new RevisionRepository(this.db);\n\t\t\tconst liveRevision = await revisionRepo.findById(existing.liveRevisionId);\n\t\t\tif (liveRevision) {\n\t\t\t\tconst draft = await revisionRepo.create({\n\t\t\t\t\tcollection: type,\n\t\t\t\t\tentryId: id,\n\t\t\t\t\tdata: liveRevision.data,\n\t\t\t\t});\n\n\t\t\t\tawait sql`\n\t\t\t\t\tUPDATE ${sql.ref(tableName)}\n\t\t\t\t\tSET draft_revision_id = ${draft.id}\n\t\t\t\t\tWHERE id = ${id}\n\t\t\t\t`.execute(this.db);\n\t\t\t}\n\t\t}\n\n\t\tawait sql`\n\t\t\tUPDATE ${sql.ref(tableName)}\n\t\t\tSET live_revision_id = NULL,\n\t\t\t\tstatus = 'draft',\n\t\t\t\tpublished_at = NULL,\n\t\t\t\tupdated_at = ${now}\n\t\t\tWHERE id = ${id}\n\t\t\tAND deleted_at IS NULL\n\t\t`.execute(this.db);\n\n\t\tinvalidateCollectionCache(type);\n\n\t\tconst updated = await this.findById(type, id);\n\t\tif (!updated) {\n\t\t\tthrow new Error(\"Content not found\");\n\t\t}\n\n\t\treturn updated;\n\t}\n\n\t/**\n\t * Set the draft revision pointer for a content item.\n\t *\n\t * Used by seed/import paths that stage a new revision's data before\n\t * promoting it to live via `publish()`.\n\t *\n\t * Validates that the content item exists and is not soft-deleted, that\n\t * the revision exists, and that the revision belongs to the same\n\t * collection and entry. Without these checks, a caller could leave the\n\t * content row pointing at a missing or unrelated revision.\n\t */\n\tasync setDraftRevision(type: string, id: string, revisionId: string): Promise<void> {\n\t\tconst existing = await this.findById(type, id);\n\t\tif (!existing) {\n\t\t\tthrow new EmDashValidationError(\"Content item not found\");\n\t\t}\n\n\t\tconst revisionRepo = new RevisionRepository(this.db);\n\t\tconst revision = await revisionRepo.findById(revisionId);\n\t\tif (!revision) {\n\t\t\tthrow new EmDashValidationError(\"Revision not found\");\n\t\t}\n\n\t\tif (revision.collection !== type || revision.entryId !== id) {\n\t\t\tthrow new EmDashValidationError(\"Revision does not belong to the specified content item\");\n\t\t}\n\n\t\tif (!(await this.replaceDraftRevision(type, id, revisionId, existing))) {\n\t\t\tthrow new ContentMutationConflictError();\n\t\t}\n\t}\n\n\tasync replaceDraftRevision(\n\t\ttype: string,\n\t\tid: string,\n\t\trevisionId: string,\n\t\texpected: Pick<ContentItem, \"version\" | \"liveRevisionId\" | \"draftRevisionId\">,\n\t): Promise<boolean> {\n\t\tconst tableName = getTableName(type);\n\t\tconst result = await sql`\n\t\t\tUPDATE ${sql.ref(tableName)}\n\t\t\tSET draft_revision_id = ${revisionId},\n\t\t\t\tversion = version + 1\n\t\t\tWHERE id = ${id}\n\t\t\tAND deleted_at IS NULL\n\t\t\tAND version = ${expected.version}\n\t\t\tAND ${nullableColumnMatch(\"live_revision_id\", expected.liveRevisionId)}\n\t\t\tAND ${nullableColumnMatch(\"draft_revision_id\", expected.draftRevisionId)}\n\t\t\tAND EXISTS (\n\t\t\t\tSELECT 1 FROM revisions\n\t\t\t\tWHERE revisions.id = ${revisionId}\n\t\t\t\tAND revisions.collection = ${type}\n\t\t\t\tAND revisions.entry_id = ${id}\n\t\t\t)\n\t\t`.execute(this.db);\n\t\treturn (result.numAffectedRows ?? 0n) > 0n;\n\t}\n\n\t/**\n\t * Discard pending draft changes\n\t *\n\t * Clears draft_revision_id. The content table columns already hold the\n\t * published version, so no data sync is needed.\n\t */\n\tasync discardDraft(type: string, id: string): Promise<ContentItem> {\n\t\tconst tableName = getTableName(type);\n\n\t\tconst existing = await this.findById(type, id);\n\t\tif (!existing) {\n\t\t\tthrow new EmDashValidationError(\"Content item not found\");\n\t\t}\n\n\t\tif (!existing.draftRevisionId) {\n\t\t\t// No draft to discard\n\t\t\treturn existing;\n\t\t}\n\n\t\t// Discarding a draft restores the state from before the draft was\n\t\t// staged — nothing about the live entry changed in between, so\n\t\t// updated_at stays at its pre-draft value (#2143).\n\t\tawait sql`\n\t\t\tUPDATE ${sql.ref(tableName)}\n\t\t\tSET draft_revision_id = NULL\n\t\t\tWHERE id = ${id}\n\t\t\tAND deleted_at IS NULL\n\t\t`.execute(this.db);\n\n\t\tconst updated = await this.findById(type, id);\n\t\tif (!updated) {\n\t\t\tthrow new Error(\"Content not found\");\n\t\t}\n\n\t\treturn updated;\n\t}\n\n\t/**\n\t * Count content items with a pending schedule.\n\t * Includes both draft-scheduled (status='scheduled') and published\n\t * posts with scheduled draft changes (status='published', scheduled_at set).\n\t */\n\tasync countScheduled(type: string): Promise<number> {\n\t\tconst tableName = getTableName(type);\n\n\t\tconst result = await sql<{ count: number }>`\n\t\t\tSELECT COUNT(id) as count FROM ${sql.ref(tableName)}\n\t\t\tWHERE scheduled_at IS NOT NULL\n\t\t\tAND deleted_at IS NULL\n\t\t`.execute(this.db);\n\n\t\treturn Number(result.rows[0]?.count || 0);\n\t}\n\n\t/**\n\t * Map database row to ContentItem\n\t * Extracts system columns and puts content fields in data\n\t * Excludes null values from data to match input semantics\n\t */\n\tprivate mapRow(type: string, row: Record<string, unknown>): ContentItem {\n\t\tconst data: Record<string, unknown> = {};\n\n\t\tfor (const [key, value] of Object.entries(row)) {\n\t\t\tif (!SYSTEM_COLUMNS.has(key) && value !== null) {\n\t\t\t\tdata[key] = deserializeValue(value);\n\t\t\t}\n\t\t}\n\n\t\treturn {\n\t\t\tid: row.id as string,\n\t\t\ttype,\n\t\t\tslug: row.slug as string | null,\n\t\t\tstatus: row.status as string,\n\t\t\tdata,\n\t\t\tauthorId: row.author_id as string | null,\n\t\t\tprimaryBylineId: (row.primary_byline_id as string | null) ?? null,\n\t\t\tcreatedAt: row.created_at as string,\n\t\t\tupdatedAt: row.updated_at as string,\n\t\t\tpublishedAt: row.published_at as string | null,\n\t\t\tscheduledAt: row.scheduled_at as string | null,\n\t\t\tliveRevisionId: (row.live_revision_id as string | null) ?? null,\n\t\t\tdraftRevisionId: (row.draft_revision_id as string | null) ?? null,\n\t\t\tversion: typeof row.version === \"number\" ? row.version : 1,\n\t\t\tlocale: (row.locale as string) ?? null,\n\t\t\ttranslationGroup: (row.translation_group as string) ?? null,\n\t\t};\n\t}\n\n\tprivate normalizeFilterScalar(\n\t\tfield: string,\n\t\ttype: FieldType,\n\t\tvalue: unknown,\n\t): NormalizedFilterScalar {\n\t\tif (type === \"number\" || type === \"integer\") {\n\t\t\tif (typeof value !== \"number\" || !Number.isFinite(value)) {\n\t\t\t\tthrow new EmDashValidationError(`Filter for field \"${field}\" must use a finite number`);\n\t\t\t}\n\t\t\tif (type === \"integer\" && !Number.isInteger(value)) {\n\t\t\t\tthrow new EmDashValidationError(`Filter for field \"${field}\" must use an integer`);\n\t\t\t}\n\t\t\treturn value;\n\t\t}\n\n\t\tif (type === \"boolean\") {\n\t\t\tif (typeof value !== \"boolean\") {\n\t\t\t\tthrow new EmDashValidationError(`Filter for field \"${field}\" must use a boolean`);\n\t\t\t}\n\t\t\treturn value ? 1 : 0;\n\t\t}\n\n\t\tif (typeof value !== \"string\") {\n\t\t\tthrow new EmDashValidationError(`Filter for field \"${field}\" must use a string`);\n\t\t}\n\t\tif (value.length > MAX_FILTER_STRING_LENGTH) {\n\t\t\tthrow new EmDashValidationError(\n\t\t\t\t`Filter value for field \"${field}\" exceeds ${MAX_FILTER_STRING_LENGTH} characters`,\n\t\t\t);\n\t\t}\n\t\treturn value;\n\t}\n\n\tprivate normalizeFieldFilter(\n\t\tfield: string,\n\t\ttype: FieldType,\n\t\tvalue: ContentFieldFilterValue,\n\t): ResolvedFieldFilter {\n\t\tif (value === null) return { column: field, kind: \"null\" };\n\t\tif (typeof value !== \"object\") {\n\t\t\treturn {\n\t\t\t\tcolumn: field,\n\t\t\t\tkind: \"exact\",\n\t\t\t\tvalue: this.normalizeFilterScalar(field, type, value),\n\t\t\t};\n\t\t}\n\t\tif (Array.isArray(value)) {\n\t\t\tthrow new EmDashValidationError(`Invalid filter for field \"${field}\"`);\n\t\t}\n\n\t\tconst record = value as Record<string, unknown>;\n\t\tconst keys = Object.keys(record);\n\t\tif (keys.length === 1 && keys[0] === \"in\") {\n\t\t\tif (!Array.isArray(record.in) || record.in.length === 0) {\n\t\t\t\tthrow new EmDashValidationError(`IN filter for field \"${field}\" must not be empty`);\n\t\t\t}\n\t\t\tif (record.in.length > MAX_IN_FILTER_VALUES) {\n\t\t\t\tthrow new EmDashValidationError(\n\t\t\t\t\t`IN filter for field \"${field}\" exceeds ${MAX_IN_FILTER_VALUES} values`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tcolumn: field,\n\t\t\t\tkind: \"in\",\n\t\t\t\tvalues: record.in.map((entry) => this.normalizeFilterScalar(field, type, entry)),\n\t\t\t};\n\t\t}\n\n\t\tconst rangeKeys = new Set([\"gt\", \"gte\", \"lt\", \"lte\"]);\n\t\tif (keys.length === 0 || keys.some((key) => !rangeKeys.has(key))) {\n\t\t\tthrow new EmDashValidationError(`Invalid filter operator for field \"${field}\"`);\n\t\t}\n\t\tif (type === \"boolean\") {\n\t\t\tthrow new EmDashValidationError(`Boolean field \"${field}\" does not support range filters`);\n\t\t}\n\n\t\tconst bounds: Partial<Record<\"gt\" | \"gte\" | \"lt\" | \"lte\", NormalizedFilterScalar>> = {};\n\t\tfor (const key of keys as Array<\"gt\" | \"gte\" | \"lt\" | \"lte\">) {\n\t\t\tif (record[key] === undefined) continue;\n\t\t\tbounds[key] = this.normalizeFilterScalar(field, type, record[key]);\n\t\t}\n\t\tif (Object.keys(bounds).length === 0) {\n\t\t\tthrow new EmDashValidationError(`Range filter for field \"${field}\" has no bounds`);\n\t\t}\n\t\treturn { column: field, kind: \"range\", bounds };\n\t}\n\n\tprivate async collectionExists(type: string): Promise<boolean> {\n\t\tconst collection = await this.db\n\t\t\t.selectFrom(\"_emdash_collections\")\n\t\t\t.where(\"slug\", \"=\", type)\n\t\t\t.select(\"id\")\n\t\t\t.executeTakeFirst();\n\t\treturn collection !== undefined;\n\t}\n\n\tprivate async resolveFieldFilters(\n\t\ttype: string,\n\t\tfilters: ContentFieldFilters | undefined,\n\t): Promise<ResolvedFieldFilter[]> {\n\t\tconst resolvedFilters = filters ?? {};\n\t\tconst fields = Object.keys(resolvedFilters);\n\t\tif (fields.length === 0) return [];\n\t\tif (fields.length > MAX_INDEXED_FIELD_FILTERS) {\n\t\t\tif (!(await this.collectionExists(type))) return [];\n\t\t\tthrow new EmDashValidationError(\n\t\t\t\t`Content list queries support at most ${MAX_INDEXED_FIELD_FILTERS} indexed field filters`,\n\t\t\t);\n\t\t}\n\t\tconst rows = await this.db\n\t\t\t.selectFrom(\"_emdash_fields as field\")\n\t\t\t.innerJoin(\"_emdash_collections as collection\", \"collection.id\", \"field.collection_id\")\n\t\t\t.where(\"collection.slug\", \"=\", type)\n\t\t\t.where(\"field.slug\", \"in\", fields)\n\t\t\t.where(\"field.indexed\", \"=\", 1)\n\t\t\t.select([\"field.slug\", \"field.type\"])\n\t\t\t.execute();\n\t\tconst metadata = new Map(rows.map((row) => [row.slug, row.type as FieldType]));\n\n\t\tif (metadata.size === 0 && !(await this.collectionExists(type))) return [];\n\n\t\tfor (const field of fields) {\n\t\t\ttry {\n\t\t\t\tvalidateIdentifier(field, \"content filter field\");\n\t\t\t} catch {\n\t\t\t\tthrow new EmDashValidationError(`Invalid content filter field: ${field}`);\n\t\t\t}\n\t\t}\n\n\t\tconst normalized = fields.map((field) => {\n\t\t\tconst fieldType = metadata.get(field);\n\t\t\tif (!fieldType || !isIndexableFieldType(fieldType)) {\n\t\t\t\tthrow new EmDashValidationError(\n\t\t\t\t\t`Cannot filter by field \"${field}\". Custom fields must be indexed before filtering.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn this.normalizeFieldFilter(field, fieldType, resolvedFilters[field]);\n\t\t});\n\t\tconst operandCount = normalized.reduce((total, filter) => {\n\t\t\tif (filter.kind === \"null\") return total;\n\t\t\tif (filter.kind === \"exact\") return total + 1;\n\t\t\tif (filter.kind === \"in\") return total + filter.values.length;\n\t\t\treturn total + Object.keys(filter.bounds).length;\n\t\t}, 0);\n\t\tif (operandCount > SQL_BATCH_SIZE) {\n\t\t\tthrow new EmDashValidationError(\n\t\t\t\t`Indexed field filters have a total operand budget of ${SQL_BATCH_SIZE}`,\n\t\t\t);\n\t\t}\n\t\treturn normalized;\n\t}\n\n\tprivate applyFieldFilters<QB extends { where: (cb: (eb: any) => unknown) => QB }>(\n\t\tquery: QB,\n\t\tfilters: ResolvedFieldFilter[],\n\t): QB {\n\t\tlet next = query;\n\t\tfor (const filter of filters) {\n\t\t\tconst column = sql.ref(filter.column);\n\t\t\tconst isPresent = sql<boolean>`${column} IS NOT NULL`;\n\t\t\tif (filter.kind === \"null\") {\n\t\t\t\tnext = next.where(() => sql<boolean>`(${isPresent}) = FALSE AND ${column} IS NULL`);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (filter.kind === \"exact\") {\n\t\t\t\tnext = next.where(\n\t\t\t\t\t() => sql<boolean>`(${isPresent}) = TRUE AND ${column} = ${filter.value}`,\n\t\t\t\t);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (filter.kind === \"in\") {\n\t\t\t\tconst values = sql.join(\n\t\t\t\t\tfilter.values.map((value) => sql`${value}`),\n\t\t\t\t\tsql`, `,\n\t\t\t\t);\n\t\t\t\tnext = next.where(() => sql<boolean>`(${isPresent}) = TRUE AND ${column} IN (${values})`);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tnext = next.where(() => sql<boolean>`(${isPresent}) = TRUE`);\n\t\t\tif (filter.bounds.gt !== undefined) {\n\t\t\t\tnext = next.where(() => sql<boolean>`${column} > ${filter.bounds.gt}`);\n\t\t\t}\n\t\t\tif (filter.bounds.gte !== undefined) {\n\t\t\t\tnext = next.where(() => sql<boolean>`${column} >= ${filter.bounds.gte}`);\n\t\t\t}\n\t\t\tif (filter.bounds.lt !== undefined) {\n\t\t\t\tnext = next.where(() => sql<boolean>`${column} < ${filter.bounds.lt}`);\n\t\t\t}\n\t\t\tif (filter.bounds.lte !== undefined) {\n\t\t\t\tnext = next.where(() => sql<boolean>`${column} <= ${filter.bounds.lte}`);\n\t\t\t}\n\t\t}\n\t\treturn next;\n\t}\n\n\t/**\n\t * Map order field names to database columns.\n\t * Only allows known fields to prevent column enumeration via crafted orderBy values.\n\t */\n\tprivate mapOrderField(field: string, sortableExtras: readonly string[] = []): string {\n\t\tconst mapped = ORDER_FIELD_COLUMNS[field];\n\t\tif (mapped) return mapped;\n\n\t\t// A collection's configured titleField/dateField are allowed as\n\t\t// sort columns. The caller passes the collection's *actual* values (resolved\n\t\t// server-side, never client-supplied), so this stays a closed set per\n\t\t// request and doesn't reopen the column-enumeration hole. The slug is a\n\t\t// validated identifier that maps directly to the column.\n\t\tif (sortableExtras.includes(field)) {\n\t\t\tvalidateIdentifier(field, \"order field\");\n\t\t\treturn field;\n\t\t}\n\n\t\tthrow new EmDashValidationError(`Invalid order field: ${field}`);\n\t}\n\n\tprivate async resolveOrderField(\n\t\ttype: string,\n\t\tfield: string,\n\t\tsortableExtras: readonly string[] = [],\n\t): Promise<ResolvedOrderField> {\n\t\ttry {\n\t\t\treturn { column: this.mapOrderField(field, sortableExtras), indexedCustomField: false };\n\t\t} catch (error) {\n\t\t\tif (!(error instanceof EmDashValidationError)) throw error;\n\t\t}\n\n\t\tconst customField = await this.db\n\t\t\t.selectFrom(\"_emdash_collections as collection\")\n\t\t\t.leftJoin(\"_emdash_fields as field\", (join) =>\n\t\t\t\tjoin\n\t\t\t\t\t.onRef(\"field.collection_id\", \"=\", \"collection.id\")\n\t\t\t\t\t.on(\"field.slug\", \"=\", field)\n\t\t\t\t\t.on(\"field.indexed\", \"=\", 1),\n\t\t\t)\n\t\t\t.where(\"collection.slug\", \"=\", type)\n\t\t\t.select([\"collection.id as collectionId\", \"field.slug as fieldSlug\"])\n\t\t\t.executeTakeFirst();\n\n\t\tif (!customField) {\n\t\t\tthrow new ContentCollectionNotFoundError(type);\n\t\t}\n\n\t\tif (!customField.fieldSlug) {\n\t\t\tthrow new EmDashValidationError(\n\t\t\t\t`Invalid order field: ${field}. Custom fields must be indexed before sorting.`,\n\t\t\t);\n\t\t}\n\n\t\tvalidateIdentifier(customField.fieldSlug, \"content order field\");\n\t\treturn { column: customField.fieldSlug, indexedCustomField: true };\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAWA,MAAM,gBAAgB;AACtB,MAAM,kBAAkB;AACxB,MAAM,kBAAkB;;;;;;;;AASxB,SAAgB,oBAAoB,OAAuB;CAC1D,MAAM,QAAQ,MACZ,MAAM,CACN,MAAM,cAAc,CACpB,KAAK,SAAS,KAAK,QAAQ,iBAAiB,OAAK,CAAC,CAClD,QAAQ,SAAS,KAAK,SAAS,EAAE;AAEnC,KAAI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