{"version":3,"file":"content-refresh-BqLuggBG.mjs","names":["isRecord","isRecord","isRecord","readString"],"sources":["../src/media/usage/projection-fingerprint.ts","../src/database/repositories/media-usage.ts","../src/media/usage/types.ts","../src/media/usage/content-fields.ts","../src/media/usage/extractor.ts","../src/media/usage/source-key.ts","../src/media/usage/content-snapshots.ts","../src/media/usage/content-refresh.ts"],"sourcesContent":["import type {\n\tMediaUsageOccurrenceInput,\n\tMediaUsageSourceInput,\n} from \"../../database/repositories/media-usage.js\";\nimport type { MediaUsageExtractionField } from \"./types.js\";\n\nexport const MEDIA_USAGE_PROJECTION_FINGERPRINT_VERSION = 1;\nconst FINGERPRINT_PREFIX = `media-usage-projection:v${MEDIA_USAGE_PROJECTION_FINGERPRINT_VERSION}:sha256:`;\nconst FINGERPRINT_PATTERN = new RegExp(`^${FINGERPRINT_PREFIX}[a-f0-9]{64}$`);\n\nexport interface MediaUsageProjectionFingerprintInput {\n\tcollectionId: string;\n\tsource: MediaUsageSourceInput;\n\toccurrences: readonly MediaUsageOccurrenceInput[];\n\textractionFields: readonly MediaUsageExtractionField[];\n}\n\nexport interface MediaUsageProjectionFingerprint {\n\tfingerprint: string;\n\tbyteLength: number;\n}\n\nexport async function buildMediaUsageProjectionFingerprint(\n\tinput: MediaUsageProjectionFingerprintInput,\n): Promise<MediaUsageProjectionFingerprint> {\n\tif (!input.collectionId) {\n\t\tthrow new Error(\"Media usage projection fingerprints require a collection identity\");\n\t}\n\tconst canonicalOccurrences = input.occurrences\n\t\t.map((occurrence) => ({\n\t\t\tfieldSlug: occurrence.fieldSlug,\n\t\t\tfieldPath: occurrence.fieldPath,\n\t\t\toccurrenceIndex: occurrence.occurrenceIndex ?? 0,\n\t\t\treferenceType: occurrence.referenceType,\n\t\t\tmediaId: occurrence.mediaId,\n\t\t\tprovider: occurrence.provider,\n\t\t\tproviderAssetId: occurrence.providerAssetId,\n\t\t\tmediaKind: occurrence.mediaKind ?? null,\n\t\t\tmimeType: occurrence.mimeType ?? null,\n\t\t}))\n\t\t.map((occurrence) => ({ occurrence, key: canonicalJson(occurrence) }))\n\t\t.toSorted((a, b) => compareCanonicalStrings(a.key, b.key))\n\t\t.map(({ occurrence }) => occurrence);\n\treturn buildCanonicalSha256Fingerprint(FINGERPRINT_PREFIX, {\n\t\tfingerprintVersion: MEDIA_USAGE_PROJECTION_FINGERPRINT_VERSION,\n\t\tcollectionId: input.collectionId,\n\t\textractionSchema: normalizeExtractionFields(input.extractionFields),\n\t\tsource: {\n\t\t\tsourceKey: input.source.sourceKey,\n\t\t\tsourceType: input.source.sourceType,\n\t\t\tcollectionSlug: input.source.collectionSlug ?? null,\n\t\t\tcontentId: input.source.contentId ?? null,\n\t\t\tsourceVariant: input.source.sourceVariant,\n\t\t\tlocale: input.source.locale ?? null,\n\t\t\ttranslationGroup: input.source.translationGroup ?? null,\n\t\t\tcontentSlug: input.source.contentSlug ?? null,\n\t\t\tcontentTitle: input.source.contentTitle ?? null,\n\t\t\tcontentStatus: input.source.contentStatus ?? null,\n\t\t\tcontentScheduledAt: input.source.contentScheduledAt ?? null,\n\t\t\tcontentDeletedAt: input.source.contentDeletedAt ?? null,\n\t\t\trevisionId: input.source.revisionId ?? null,\n\t\t\tschemaVersion: input.source.schemaVersion ?? 1,\n\t\t\tsourceCompleteness: input.source.sourceCompleteness ?? \"complete\",\n\t\t},\n\t\toccurrences: canonicalOccurrences,\n\t});\n}\n\nexport async function buildCanonicalSha256Fingerprint(\n\tprefix: string,\n\tpayload: unknown,\n): Promise<MediaUsageProjectionFingerprint> {\n\tconst encodedPayload = new TextEncoder().encode(canonicalJson(payload));\n\tconst digest = await crypto.subtle.digest(\"SHA-256\", encodedPayload);\n\tconst hex = Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, \"0\")).join(\n\t\t\"\",\n\t);\n\treturn {\n\t\tfingerprint: `${prefix}${hex}`,\n\t\tbyteLength: encodedPayload.byteLength,\n\t};\n}\n\nfunction normalizeExtractionFields(\n\tfields: readonly MediaUsageExtractionField[],\n): Record<string, unknown>[] {\n\treturn fields\n\t\t.map((field) => {\n\t\t\tif (field.type !== \"repeater\") return { slug: field.slug, type: field.type };\n\t\t\treturn {\n\t\t\t\tslug: field.slug,\n\t\t\t\ttype: field.type,\n\t\t\t\tsubFields: (field.validation?.subFields ?? [])\n\t\t\t\t\t.map((subField) => ({ slug: subField.slug, type: subField.type }))\n\t\t\t\t\t.toSorted((a, b) => compareCanonicalStrings(a.slug, b.slug)),\n\t\t\t};\n\t\t})\n\t\t.toSorted((a, b) => compareCanonicalStrings(String(a.slug), String(b.slug)));\n}\n\nfunction compareCanonicalStrings(a: string, b: string): number {\n\treturn a < b ? -1 : a > b ? 1 : 0;\n}\n\nexport function isMediaUsageProjectionFingerprint(value: string | null | undefined): boolean {\n\treturn typeof value === \"string\" && FINGERPRINT_PATTERN.test(value);\n}\n\nfunction canonicalJson(value: unknown): string {\n\treturn JSON.stringify(canonicalize(value));\n}\n\nfunction canonicalize(value: unknown): unknown {\n\tif (value === undefined) return null;\n\tif (typeof value === \"bigint\") return value.toString();\n\tif (typeof value === \"number\") return Number.isFinite(value) ? value : null;\n\tif (Array.isArray(value)) return value.map((item) => canonicalize(item));\n\tif (!isRecord(value)) return value;\n\n\tconst canonical: Record<string, unknown> = {};\n\tfor (const key of Object.keys(value).toSorted()) {\n\t\tcanonical[key] = canonicalize(value[key]);\n\t}\n\treturn canonical;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n","import {\n\tsql,\n\ttype ExpressionBuilder,\n\ttype Kysely,\n\ttype RawBuilder,\n\ttype Selectable,\n\ttype Transaction,\n\ttype Updateable,\n} from \"kysely\";\nimport { ulid } from \"ulidx\";\n\nimport { isMediaUsageProjectionFingerprint } from \"../../media/usage/projection-fingerprint.js\";\nimport type { MediaUsageContentSourceVariant } from \"../../media/usage/source-key.js\";\nimport type { MediaKind, MediaUsageReferenceType } from \"../../media/usage/types.js\";\nimport { chunks, SQL_BATCH_SIZE } from \"../../utils/chunks.js\";\nimport { isPostgres } from \"../dialect-helpers.js\";\nimport { withTransaction } from \"../transaction.js\";\nimport type {\n\tDatabase,\n\tMediaUsageIndexStatusTable,\n\tMediaUsageSourceTable,\n\tMediaUsageTable,\n} from \"../types.js\";\nimport { validateIdentifier } from \"../validate.js\";\nimport { decodeCursor, encodeCursor, InvalidCursorError, type FindManyResult } from \"./types.js\";\n\ntype DatabaseExecutor = Kysely<Database> | Transaction<Database>;\ntype MediaUsageSourceNullableStringColumn =\n\t| \"collection_id\"\n\t| \"source_fingerprint\"\n\t| \"source_updated_at\"\n\t| \"revision_id\"\n\t| \"updated_at\"\n\t| \"last_attempted_at\"\n\t| \"last_error_code\";\nconst OCCURRENCE_BIND_COLUMNS = 13;\nexport const MEDIA_USAGE_GENERATION_WRITE_LEASE_MS = 60 * 60 * 1000;\nconst OCCURRENCE_INSERT_BATCH_SIZE = Math.max(\n\t1,\n\tMath.floor(SQL_BATCH_SIZE / OCCURRENCE_BIND_COLUMNS),\n);\n\nfunction cleanupDeleteBatchSize(cleanupLease: MediaUsageCleanupLease | undefined): number {\n\treturn cleanupLease ? SQL_BATCH_SIZE - 3 : SQL_BATCH_SIZE;\n}\n\nfunction canIssueCleanupStatement(canIssueStatement: (() => boolean) | undefined): boolean {\n\treturn canIssueStatement?.() ?? true;\n}\n\nfunction cleanupDurationSeconds(value: number): number {\n\tif (!Number.isSafeInteger(value) || value < 0) {\n\t\tthrow new Error(\"Media usage cleanup duration must be a non-negative whole number of seconds\");\n\t}\n\treturn value;\n}\n\nconst CONTENT_SOURCE_ELIGIBILITY = sql<boolean>`(\n\ts.source_variant = 'draft_overlay'\n\tOR (\n\t\ts.source_variant = 'columns'\n\t\tAND (\n\t\t\ts.content_status = 'published'\n\t\t\tOR NOT EXISTS (\n\t\t\t\tSELECT 1\n\t\t\t\tFROM _emdash_media_usage_sources AS overlay\n\t\t\t\tWHERE overlay.source_type = 'content'\n\t\t\t\t\tAND overlay.collection_slug = s.collection_slug\n\t\t\t\t\tAND overlay.content_id = s.content_id\n\t\t\t\t\tAND overlay.source_variant = 'draft_overlay'\n\t\t\t\t\tAND ${contentSourceMatchesActiveCollection(\"overlay\", \"s.collection_id\")}\n\t\t\t)\n\t\t)\n\t)\n)`;\n\ntype ContentSourceAlias = \"deleted_source\" | \"overlay\" | \"s\" | \"state\";\ntype CurrentCollectionIdReference = \"collection.id\" | \"page.collection_id\" | \"s.collection_id\";\n\nfunction contentSourceMatchesActiveCollection(\n\tsource: ContentSourceAlias,\n\tcurrentCollectionId: CurrentCollectionIdReference,\n): RawBuilder<boolean> {\n\treturn sql<boolean>`(\n\t\tNOT EXISTS (\n\t\t\tSELECT 1\n\t\t\tFROM _emdash_media_usage_activation AS activation\n\t\t\tWHERE activation.task_key = 'incremental_capture'\n\t\t\t\tAND activation.state = 'active'\n\t\t)\n\t\tOR (\n\t\t\t${sql.ref(`${source}.collection_id`)} = ${sql.ref(currentCollectionId)}\n\t\t\tAND ${sql.ref(`${source}.identity_version`)} = 1\n\t\t)\n\t)`;\n}\n\nexport interface MediaUsageSourceInput {\n\tsourceKey: string;\n\tsourceType: string;\n\tcollectionId?: string | null;\n\tcollectionSlug?: string | null;\n\tcontentId?: string | null;\n\tsourceVariant: MediaUsageContentSourceVariant;\n\tlocale?: string | null;\n\ttranslationGroup?: string | null;\n\tcontentSlug?: string | null;\n\tcontentTitle?: string | null;\n\tcontentStatus?: string | null;\n\tcontentScheduledAt?: string | null;\n\tcontentDeletedAt?: string | null;\n\trevisionId?: string | null;\n\tschemaVersion?: number;\n\tsourceUpdatedAt?: string | null;\n\tsourceVersion?: number | null;\n\tsourceFingerprint?: string | null;\n\tidentityVersion?: number | null;\n\tsourceCompleteness?: MediaUsageSourceCompleteness;\n\tlastAttemptedAt?: string | null;\n\tlastErrorCode?: string | null;\n}\n\nexport interface MediaUsageOccurrenceInput {\n\tfieldSlug: string;\n\tfieldPath: string;\n\toccurrenceIndex?: number;\n\treferenceType: MediaUsageReferenceType;\n\tmediaId: string | null;\n\tprovider: string;\n\tproviderAssetId: string;\n\tmediaKind?: MediaKind | null;\n\tmimeType?: string | null;\n}\n\nexport interface MediaUsageSource {\n\tsourceKey: string;\n\tsourceType: string;\n\tcollectionId: string | null;\n\tcollectionSlug: string | null;\n\tcontentId: string | null;\n\tsourceVariant: string;\n\tlocale: string | null;\n\ttranslationGroup: string | null;\n\tcontentSlug: string | null;\n\tcontentTitle: string | null;\n\tcontentStatus: string | null;\n\tcontentScheduledAt: string | null;\n\tcontentDeletedAt: string | null;\n\trevisionId: string | null;\n\tcurrentGeneration: string;\n\tschemaVersion: number;\n\tsourceUpdatedAt: string | null;\n\tsourceVersion: number | null;\n\tsourceFingerprint: string | null;\n\tidentityVersion: number | null;\n\tsourceCompleteness: string;\n\tlastAttemptedAt: string | null;\n\tlastErrorCode: string | null;\n\tindexedAt: string;\n\tcreatedAt: string;\n\tupdatedAt: string;\n}\n\nexport interface MediaUsageGuardedReplaceResult {\n\treplaced: boolean;\n\tunchanged: boolean;\n\t/** Populated only when a guarded replacement did not win the current source row. */\n\tsource: MediaUsageSource | null;\n}\n\nexport interface MediaUsageGuardedDeleteResult {\n\tdeleted: boolean;\n\tsource: MediaUsageSource | null;\n}\n\nexport interface MediaUsageGuardedAbsentDeleteResult extends MediaUsageGuardedDeleteResult {\n\tcontentPresent: boolean;\n}\n\nexport interface MediaUsageGuardedAttemptResult {\n\tattempted: boolean;\n\t/** Populated only when a guarded attempted mark did not win the current source row. */\n\tsource: MediaUsageSource | null;\n}\n\nexport interface MediaUsageSourceGenerationDeletionMeasurement {\n\toccurrenceCount: number;\n\toccurrenceBytes: number;\n\texceedsOccurrenceLimit: boolean;\n}\n\nexport interface MediaUsageCleanupCursor {\n\tcreatedAt: string;\n\tid: string;\n}\n\nexport interface MediaUsageCleanupClaim {\n\tleaseToken: string;\n\tcursor: MediaUsageCleanupCursor | null;\n\tclaimedAt: string;\n\tscanBeforeAt: string;\n\tconsecutiveFailures: number;\n}\n\nexport interface MediaUsageCleanupCandidate {\n\tid: string;\n\tsourceKey: string;\n\tgeneration: string;\n\tcreatedAt: string;\n\tcurrentGeneration: string | null;\n\tindexedAt: string | null;\n\twriteLeaseExpiresAt: string | null;\n}\n\nexport interface MediaUsageCleanupLease {\n\tleaseToken: string;\n}\n\nexport interface MediaUsageCleanupDeleteOptions {\n\tcandidateIds?: readonly string[];\n\tcleanupLease?: MediaUsageCleanupLease;\n\tcanIssueStatement?: () => boolean;\n}\n\nexport interface MediaUsageCleanupCompletion {\n\tleaseToken: string;\n\tnextCursor: MediaUsageCleanupCursor | null;\n\tsweepComplete: boolean;\n\tcandidateCount: number;\n\tdeletedOrphans: number;\n\tdeletedStale: number;\n\tdeletedAbandoned: number;\n\tdeletedWriteLeases: number;\n\tbacklogLowerBound: number;\n\tscanHasMore: boolean;\n\tdurationMs: number;\n}\n\nexport interface MediaUsageIndexStatusRepairInput extends MediaUsageIndexStatusIdentity {\n\trunToken: string;\n\tschemaVersion?: number;\n\tstartedAt: string;\n\tupdatedAt?: string;\n}\n\nexport interface MediaUsageIndexStatusFinalizeInput extends MediaUsageIndexStatusIdentity {\n\trunToken: string;\n\tstatus: Exclude<MediaUsageIndexStatusValue, \"never\" | \"running\" | \"stale\">;\n\tschemaVersion?: number;\n\tcompletedAt: string;\n\tindexedSourceCount?: number;\n\tfailedSourceCount?: number;\n\tlastErrorCode?: string | null;\n\tupdatedAt?: string;\n}\n\nexport interface MediaUsageIndexStatusEpochRepairInput extends MediaUsageIndexStatusIdentity {\n\tcollectionId: string;\n\trunToken: string;\n\tschemaVersion: number;\n}\n\nexport interface MediaUsageIndexStatusEpochRepairRun {\n\tchangeEpoch: number | string;\n\tstartedAt: string;\n}\n\nexport interface MediaUsageIndexStatusEpochFinalizeInput extends MediaUsageIndexStatusEpochRepairInput {\n\tstartingEpoch: number | string;\n\tstatus: Exclude<MediaUsageIndexStatusValue, \"never\" | \"running\" | \"stale\">;\n\tindexedSourceCount: number;\n\tfailedSourceCount: number;\n\tlastErrorCode: string | null;\n}\n\nexport interface MediaUsageIncrementalStatusIdentity {\n\tcollectionId: string;\n\tcollectionSlug: string;\n}\n\nexport interface MediaUsageGuardedIndexStatusResult {\n\tfinalized: boolean;\n\tstatus: MediaUsageIndexStatus | null;\n}\n\nexport type MediaUsageSourceCompleteness =\n\t| \"unknown\"\n\t| \"complete\"\n\t| \"partial\"\n\t| \"failed\"\n\t| \"unsupported\";\n\nexport type MediaUsageIndexStatusValue =\n\t| \"never\"\n\t| \"running\"\n\t| \"complete\"\n\t| \"partial\"\n\t| \"failed\"\n\t| \"stale\";\n\nexport interface MediaUsageIndexStatusIdentity {\n\tadapterId: string;\n\tscopeType: string;\n\tscopeKey: string;\n}\n\nexport interface MediaUsageIndexStatusInput extends MediaUsageIndexStatusIdentity {\n\tstatus: MediaUsageIndexStatusValue;\n\tschemaVersion?: number;\n\tstartedAt?: string | null;\n\tcompletedAt?: string | null;\n\tcursor?: string | null;\n\tindexedSourceCount?: number;\n\tfailedSourceCount?: number;\n\tlastErrorCode?: string | null;\n\tupdatedAt?: string;\n}\n\nexport interface MediaUsageIndexStatus extends MediaUsageIndexStatusIdentity {\n\tstatus: string;\n\tschemaVersion: number;\n\tstartedAt: string | null;\n\tcompletedAt: string | null;\n\tcursor: string | null;\n\tindexedSourceCount: number;\n\tfailedSourceCount: number;\n\tlastErrorCode: string | null;\n\tupdatedAt: string;\n}\n\nexport interface FindMediaUsageOptions {\n\tlimit?: number;\n\tcursor?: string;\n}\n\nexport interface MediaUsageCollectionIndexStatusScope {\n\tcollectionSlug: string;\n\tstatus: string | null;\n\tschemaVersion: number | null;\n\treconciliationRequired: boolean;\n}\n\nexport interface MediaUsageEntrySource {\n\tsource: MediaUsageSource;\n\toccurrences: MediaUsageOccurrence[];\n}\n\nexport interface MediaUsageEntryGroup {\n\tcollectionSlug: string;\n\tcontentId: string;\n\tcontentDeletedAt: string | null;\n\tsources: MediaUsageEntrySource[];\n}\n\ninterface MediaUsageSourceRow {\n\tsource_key: string;\n\tsource_type: string;\n\tcollection_id: string | null;\n\tcollection_slug: string | null;\n\tcontent_id: string | null;\n\tsource_variant: string;\n\tlocale: string | null;\n\ttranslation_group: string | null;\n\tcontent_slug: string | null;\n\tcontent_title: string | null;\n\tcontent_status: string | null;\n\tcontent_scheduled_at: string | null;\n\tcontent_deleted_at: string | null;\n\trevision_id: string | null;\n\tcurrent_generation: string;\n\tschema_version: number;\n\tsource_updated_at: string | null;\n\tsource_version: number | null;\n\tsource_fingerprint: string | null;\n\tidentity_version: number | null;\n\tsource_completeness: string;\n\tlast_attempted_at: string | null;\n\tlast_error_code: string | null;\n\tindexed_at: string;\n\tcreated_at: string;\n\tupdated_at: string;\n}\n\nexport interface MediaUsageOccurrence {\n\tid: string;\n\tsourceKey: string;\n\tgeneration: string;\n\tfieldSlug: string;\n\tfieldPath: string;\n\toccurrenceIndex: number;\n\treferenceType: string;\n\tmediaId: string | null;\n\tprovider: string;\n\tproviderAssetId: string;\n\tmediaKind: string | null;\n\tmimeType: string | null;\n\tcreatedAt: string;\n}\n\nexport interface MediaUsageRecord {\n\tsource: MediaUsageSource;\n\toccurrence: MediaUsageOccurrence;\n}\n\ninterface JoinedUsageRow {\n\tsource_key: string;\n\tsource_type: string;\n\tcollection_id: string | null;\n\tcollection_slug: string | null;\n\tcontent_id: string | null;\n\tsource_variant: string;\n\tlocale: string | null;\n\ttranslation_group: string | null;\n\tcontent_slug: string | null;\n\tcontent_title: string | null;\n\tcontent_status: string | null;\n\tcontent_scheduled_at: string | null;\n\tcontent_deleted_at: string | null;\n\trevision_id: string | null;\n\tcurrent_generation: string;\n\tschema_version: number;\n\tsource_updated_at: string | null;\n\tsource_version: number | null;\n\tsource_fingerprint: string | null;\n\tidentity_version: number | null;\n\tsource_completeness: string;\n\tlast_attempted_at: string | null;\n\tlast_error_code: string | null;\n\tindexed_at: string;\n\tsource_created_at: string;\n\tsource_row_updated_at: string;\n\toccurrence_id: string;\n\tgeneration: string;\n\tfield_slug: string;\n\tfield_path: string;\n\toccurrence_index: number;\n\treference_type: string;\n\tmedia_id: string | null;\n\tprovider: string;\n\tprovider_asset_id: string;\n\tmedia_kind: string | null;\n\tmime_type: string | null;\n\toccurrence_created_at: string;\n}\n\ninterface GroupedUsageRow extends JoinedUsageRow {\n\tentry_deleted_at: string | null;\n\thas_more: number;\n}\n\n/** Persistence-only repository for the internal media usage projection tables. */\nexport class MediaUsageRepository {\n\tconstructor(private db: Kysely<Database>) {}\n\n\tasync replaceSource(\n\t\tsource: MediaUsageSourceInput,\n\t\toccurrences: readonly MediaUsageOccurrenceInput[],\n\t): Promise<MediaUsageSource> {\n\t\tconst generation = ulid();\n\n\t\tconst admitted = await this.withGenerationWriteLease(\n\t\t\tsource,\n\t\t\tgeneration,\n\t\t\tasync (leaseToken, now) => {\n\t\t\t\tawait withTransaction(this.db, async (trx) => {\n\t\t\t\t\tif (!(await this.lockCanonicalSourceCollection(trx, source))) {\n\t\t\t\t\t\tthrow new Error(`Media usage collection is no longer current for ${source.sourceKey}`);\n\t\t\t\t\t}\n\t\t\t\t\tawait this.insertOccurrences(trx, source.sourceKey, generation, occurrences, now);\n\t\t\t\t\tconst promoted = await this.upsertSource(trx, source, generation, now, leaseToken);\n\t\t\t\t\tif (!promoted) {\n\t\t\t\t\t\tthrow new Error(`Media usage generation lease expired for ${source.sourceKey}`);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t},\n\t\t);\n\t\tif (!admitted) {\n\t\t\tthrow new Error(`Media usage collection is no longer current for ${source.sourceKey}`);\n\t\t}\n\n\t\tconst replaced = await this.findSource(source.sourceKey);\n\t\tif (!replaced) {\n\t\t\tthrow new Error(`Media usage source ${source.sourceKey} was not persisted`);\n\t\t}\n\t\treturn replaced;\n\t}\n\tasync replaceSourceIfCurrent(\n\t\tsource: MediaUsageSourceInput,\n\t\toccurrences: readonly MediaUsageOccurrenceInput[],\n\t\texpectedCurrentGeneration: string | null,\n\t): Promise<MediaUsageGuardedReplaceResult> {\n\t\tif (\n\t\t\texpectedCurrentGeneration !== null &&\n\t\t\t(await this.projectionMatchesCurrentGeneration(source, expectedCurrentGeneration))\n\t\t) {\n\t\t\treturn { replaced: false, unchanged: true, source: null };\n\t\t}\n\t\tconst generation = ulid();\n\t\tlet replaced = false;\n\n\t\tawait this.withGenerationWriteLease(source, generation, async (leaseToken, now) => {\n\t\t\tconst row = this.buildSourceRow(source, generation, now);\n\t\t\tawait withTransaction(this.db, async (trx) => {\n\t\t\t\tif (!(await this.lockCanonicalSourceCollection(trx, source))) return;\n\t\t\t\tawait this.insertOccurrences(trx, source.sourceKey, generation, occurrences, now);\n\t\t\t\tif (expectedCurrentGeneration === null) {\n\t\t\t\t\treplaced = await this.insertSourceIfAbsent(trx, row, leaseToken);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\treplaced = await this.updateSourceIfGeneration(\n\t\t\t\t\ttrx,\n\t\t\t\t\trow,\n\t\t\t\t\texpectedCurrentGeneration,\n\t\t\t\t\tleaseToken,\n\t\t\t\t);\n\t\t\t});\n\t\t});\n\n\t\treturn {\n\t\t\treplaced,\n\t\t\tunchanged: false,\n\t\t\tsource: replaced ? null : await this.findSource(source.sourceKey),\n\t\t};\n\t}\n\n\tasync findSource(sourceKey: string): Promise<MediaUsageSource | null> {\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"_emdash_media_usage_sources\")\n\t\t\t.selectAll()\n\t\t\t.where(\"source_key\", \"=\", sourceKey)\n\t\t\t.executeTakeFirst();\n\n\t\treturn row ? rowToSource(row) : null;\n\t}\n\n\tasync findSources(sourceKeys: readonly string[]): Promise<Map<string, MediaUsageSource>> {\n\t\tconst uniqueSourceKeys = [...new Set(sourceKeys)];\n\t\tconst sources = new Map<string, MediaUsageSource>();\n\t\tif (uniqueSourceKeys.length === 0) return sources;\n\n\t\tfor (const sourceKeyBatch of chunks(uniqueSourceKeys, SQL_BATCH_SIZE)) {\n\t\t\tconst rows = await this.db\n\t\t\t\t.selectFrom(\"_emdash_media_usage_sources\")\n\t\t\t\t.selectAll()\n\t\t\t\t.where(\"source_key\", \"in\", sourceKeyBatch)\n\t\t\t\t.execute();\n\t\t\tfor (const row of rows) {\n\t\t\t\tconst source = rowToSource(row);\n\t\t\t\tsources.set(source.sourceKey, source);\n\t\t\t}\n\t\t}\n\n\t\treturn sources;\n\t}\n\n\tasync measureSourceGenerationDeletion(\n\t\tsourceKey: string,\n\t\tgeneration: string,\n\t\tmaxOccurrences: number,\n\t): Promise<MediaUsageSourceGenerationDeletionMeasurement> {\n\t\tif (!Number.isSafeInteger(maxOccurrences) || maxOccurrences < 0) {\n\t\t\tthrow new Error(\"Media usage deletion measurement requires a non-negative row limit\");\n\t\t}\n\t\tconst payload = sql<string>`\n\t\t\tCOALESCE(field_slug, '') || COALESCE(field_path, '') ||\n\t\t\tCOALESCE(reference_type, '') || COALESCE(media_id, '') ||\n\t\t\tCOALESCE(provider, '') || COALESCE(provider_asset_id, '') ||\n\t\t\tCOALESCE(media_kind, '') || COALESCE(mime_type, '')\n\t\t`;\n\t\tconst occurrenceBytes = isPostgres(this.db)\n\t\t\t? sql<number>`octet_length(${payload})`\n\t\t\t: sql<number>`length(CAST(${payload} AS BLOB))`;\n\t\tconst rows = await this.db\n\t\t\t.selectFrom(\"_emdash_media_usage\")\n\t\t\t.select(occurrenceBytes.as(\"occurrence_bytes\"))\n\t\t\t.where(\"source_key\", \"=\", sourceKey)\n\t\t\t.where(\"generation\", \"=\", generation)\n\t\t\t.limit(maxOccurrences + 1)\n\t\t\t.execute();\n\n\t\treturn {\n\t\t\toccurrenceCount: rows.length,\n\t\t\toccurrenceBytes: rows.reduce((total, row) => total + Number(row.occurrence_bytes), 0),\n\t\t\texceedsOccurrenceLimit: rows.length > maxOccurrences,\n\t\t};\n\t}\n\n\tasync replaceSourceIfMatching(\n\t\tsource: MediaUsageSourceInput,\n\t\toccurrences: readonly MediaUsageOccurrenceInput[],\n\t\texpectedSource: MediaUsageSource | null,\n\t): Promise<MediaUsageGuardedReplaceResult> {\n\t\tif (\n\t\t\texpectedSource !== null &&\n\t\t\t(await this.projectionMatchesExpectedSource(source, expectedSource))\n\t\t) {\n\t\t\treturn { replaced: false, unchanged: true, source: null };\n\t\t}\n\t\tconst generation = ulid();\n\t\tlet replaced = false;\n\n\t\tawait this.withGenerationWriteLease(source, generation, async (leaseToken, now) => {\n\t\t\tconst row = this.buildSourceRow(source, generation, now);\n\t\t\tawait withTransaction(this.db, async (trx) => {\n\t\t\t\tif (!(await this.lockCanonicalSourceCollection(trx, source))) return;\n\t\t\t\tawait this.insertOccurrences(trx, source.sourceKey, generation, occurrences, now);\n\t\t\t\tif (expectedSource === null) {\n\t\t\t\t\treplaced = await this.insertSourceIfAbsent(trx, row, leaseToken);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\treplaced = await this.updateSourceIfMatching(trx, row, expectedSource, leaseToken);\n\t\t\t});\n\t\t});\n\n\t\treturn {\n\t\t\treplaced,\n\t\t\tunchanged: false,\n\t\t\tsource: replaced ? null : await this.findSource(source.sourceKey),\n\t\t};\n\t}\n\n\tasync markSourceAttempted(source: MediaUsageSourceInput): Promise<MediaUsageSource> {\n\t\tif (source.collectionId !== undefined && source.collectionId !== null) {\n\t\t\tconst expectedSource = await this.findSource(source.sourceKey);\n\t\t\tconst result = await this.markSourceAttemptedIfMatching(source, expectedSource);\n\t\t\tif (!result.attempted) {\n\t\t\t\tthrow new Error(`Canonical media usage source ${source.sourceKey} is no longer current`);\n\t\t\t}\n\t\t\tconst attempted = await this.findSource(source.sourceKey);\n\t\t\tif (!attempted) {\n\t\t\t\tthrow new Error(`Media usage source ${source.sourceKey} was not persisted`);\n\t\t\t}\n\t\t\treturn attempted;\n\t\t}\n\n\t\tconst generation = ulid();\n\t\tawait this.withGenerationWriteLease(source, generation, async (leaseToken, now) => {\n\t\t\tconst row = this.buildAttemptedSourceRow(source, generation, now);\n\t\t\tconst updates = this.attemptedSourceUpdateSet(source, row);\n\t\t\tconst result = await this.db\n\t\t\t\t.insertInto(\"_emdash_media_usage_sources\")\n\t\t\t\t.values(row)\n\t\t\t\t.onConflict((oc) => oc.column(\"source_key\").doUpdateSet(updates))\n\t\t\t\t.executeTakeFirst();\n\t\t\tif ((result.numInsertedOrUpdatedRows ?? 0n) <= 0n) {\n\t\t\t\tthrow new Error(`Media usage generation lease expired for ${source.sourceKey}`);\n\t\t\t}\n\t\t});\n\n\t\tconst attempted = await this.findSource(source.sourceKey);\n\t\tif (!attempted) {\n\t\t\tthrow new Error(`Media usage source ${source.sourceKey} was not persisted`);\n\t\t}\n\t\treturn attempted;\n\t}\n\n\tasync markSourceAttemptedIfMatching(\n\t\tsource: MediaUsageSourceInput,\n\t\texpectedSource: MediaUsageSource | null,\n\t): Promise<MediaUsageGuardedAttemptResult> {\n\t\tconst generation = ulid();\n\t\tlet attempted = false;\n\n\t\tif (expectedSource === null) {\n\t\t\tawait this.withGenerationWriteLease(source, generation, async (leaseToken, now) => {\n\t\t\t\tconst row = this.buildAttemptedSourceRow(source, generation, now);\n\t\t\t\tawait withTransaction(this.db, async (trx) => {\n\t\t\t\t\tif (!(await this.lockCanonicalSourceCollection(trx, source))) return;\n\t\t\t\t\tattempted = await this.persistSourceIfWriteLease(\n\t\t\t\t\t\ttrx,\n\t\t\t\t\t\trow,\n\t\t\t\t\t\tleaseToken,\n\t\t\t\t\t\tsql`ON CONFLICT (source_key) DO NOTHING`,\n\t\t\t\t\t);\n\t\t\t\t});\n\t\t\t});\n\t\t} else {\n\t\t\tconst row = this.buildAttemptedSourceRow(source, generation, new Date().toISOString());\n\t\t\tawait withTransaction(this.db, async (trx) => {\n\t\t\t\tif (!(await this.lockCanonicalSourceCollection(trx, source))) return;\n\t\t\t\tattempted = await this.updateAttemptedSourceIfMatching(trx, source, row, expectedSource);\n\t\t\t});\n\t\t}\n\n\t\treturn {\n\t\t\tattempted,\n\t\t\tsource: attempted ? null : await this.findSource(source.sourceKey),\n\t\t};\n\t}\n\n\tasync findActiveEntryCountsByMediaIds(mediaIds: readonly string[]): Promise<Map<string, number>> {\n\t\tconst uniqueMediaIds = [...new Set(mediaIds)];\n\t\tconst counts = new Map(uniqueMediaIds.map((mediaId) => [mediaId, 0]));\n\n\t\tfor (const mediaIdBatch of chunks(uniqueMediaIds, SQL_BATCH_SIZE)) {\n\t\t\tconst visibleEntries = this.currentContentMediaUsageBaseQuery()\n\t\t\t\t.select([\n\t\t\t\t\t\"u.media_id as media_id\",\n\t\t\t\t\t\"s.collection_slug as collection_slug\",\n\t\t\t\t\t\"s.content_id as content_id\",\n\t\t\t\t])\n\t\t\t\t.where(\"u.media_id\", \"in\", mediaIdBatch)\n\t\t\t\t.where((eb) =>\n\t\t\t\t\teb.not(\n\t\t\t\t\t\teb.exists(\n\t\t\t\t\t\t\teb\n\t\t\t\t\t\t\t\t.selectFrom(\"_emdash_media_usage_sources as deleted_source\")\n\t\t\t\t\t\t\t\t.select(\"deleted_source.source_key\")\n\t\t\t\t\t\t\t\t.where(\"deleted_source.source_type\", \"=\", \"content\")\n\t\t\t\t\t\t\t\t.whereRef(\"deleted_source.collection_slug\", \"=\", \"s.collection_slug\")\n\t\t\t\t\t\t\t\t.whereRef(\"deleted_source.content_id\", \"=\", \"s.content_id\")\n\t\t\t\t\t\t\t\t.where(\"deleted_source.source_variant\", \"in\", [\"columns\", \"draft_overlay\"])\n\t\t\t\t\t\t\t\t.where(contentSourceMatchesActiveCollection(\"deleted_source\", \"collection.id\"))\n\t\t\t\t\t\t\t\t.where(\"deleted_source.content_deleted_at\", \"is not\", null),\n\t\t\t\t\t\t),\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t\t.distinct()\n\t\t\t\t.as(\"visible_entries\");\n\n\t\t\tconst rows = await this.db\n\t\t\t\t.selectFrom(visibleEntries)\n\t\t\t\t.select(\"media_id\")\n\t\t\t\t.select((eb) => eb.fn.countAll<number>().as(\"usage_count\"))\n\t\t\t\t.groupBy(\"media_id\")\n\t\t\t\t.execute();\n\n\t\t\tfor (const row of rows) {\n\t\t\t\tif (row.media_id !== null) counts.set(row.media_id, Number(row.usage_count));\n\t\t\t}\n\t\t}\n\n\t\treturn counts;\n\t}\n\n\tasync findCollectionIndexStatusScopes(\n\t\tidentity: Pick<MediaUsageIndexStatusIdentity, \"adapterId\" | \"scopeType\">,\n\t): Promise<MediaUsageCollectionIndexStatusScope[]> {\n\t\tconst rows = await this.db\n\t\t\t.selectFrom(\"_emdash_collections as collection\")\n\t\t\t.leftJoin(\"_emdash_media_usage_index_status as status\", (join) =>\n\t\t\t\tjoin\n\t\t\t\t\t.on(\"status.adapter_id\", \"=\", identity.adapterId)\n\t\t\t\t\t.on(\"status.scope_type\", \"=\", identity.scopeType)\n\t\t\t\t\t.onRef(\"status.scope_key\", \"=\", \"collection.slug\"),\n\t\t\t)\n\t\t\t.select([\n\t\t\t\t\"collection.slug as collection_slug\",\n\t\t\t\t\"status.status as status\",\n\t\t\t\t\"status.schema_version as schema_version\",\n\t\t\t\t\"status.reconciliation_required as reconciliation_required\",\n\t\t\t])\n\t\t\t.orderBy(\"collection.slug\", \"asc\")\n\t\t\t.execute();\n\n\t\treturn rows.map((row) => ({\n\t\t\tcollectionSlug: row.collection_slug,\n\t\t\tstatus: row.status,\n\t\t\tschemaVersion: row.schema_version === null ? null : Number(row.schema_version),\n\t\t\treconciliationRequired:\n\t\t\t\trow.reconciliation_required !== null && Number(row.reconciliation_required) !== 0,\n\t\t}));\n\t}\n\n\tasync findCurrentEntryUsagePageByMediaId(\n\t\tmediaId: string,\n\t\toptions: FindMediaUsageOptions = {},\n\t): Promise<FindManyResult<MediaUsageEntryGroup>> {\n\t\tconst requestedLimit = Math.floor(options.limit ?? 50);\n\t\tconst limit = Number.isFinite(requestedLimit) ? Math.min(Math.max(1, requestedLimit), 100) : 50;\n\t\tconst cursor = options.cursor ? decodeCursor(options.cursor) : null;\n\t\tif (cursor && (cursor.orderValue.length === 0 || cursor.id.length === 0)) {\n\t\t\tthrow new InvalidCursorError(options.cursor ?? \"\");\n\t\t}\n\t\tlet matchedGroups = this.currentContentMediaUsageBaseQuery()\n\t\t\t.select([\n\t\t\t\t\"collection.id as collection_id\",\n\t\t\t\t\"s.collection_slug as collection_slug\",\n\t\t\t\t\"s.content_id as content_id\",\n\t\t\t])\n\t\t\t.where(\"u.media_id\", \"=\", mediaId)\n\t\t\t.distinct();\n\t\tif (cursor) {\n\t\t\tmatchedGroups = matchedGroups.where((eb) =>\n\t\t\t\teb.or([\n\t\t\t\t\teb(\"s.collection_slug\", \">\", cursor.orderValue),\n\t\t\t\t\teb.and([\n\t\t\t\t\t\teb(\"s.collection_slug\", \"=\", cursor.orderValue),\n\t\t\t\t\t\teb(\"s.content_id\", \">\", cursor.id),\n\t\t\t\t\t]),\n\t\t\t\t]),\n\t\t\t);\n\t\t}\n\t\tmatchedGroups = matchedGroups\n\t\t\t.orderBy(\"s.collection_slug\", \"asc\")\n\t\t\t.orderBy(\"s.content_id\", \"asc\")\n\t\t\t.limit(limit + 1);\n\n\t\tconst rows: GroupedUsageRow[] = await this.db\n\t\t\t.with(\"matched_groups\", () => matchedGroups)\n\t\t\t.with(\"page_groups\", (db) =>\n\t\t\t\tdb\n\t\t\t\t\t.selectFrom(\"matched_groups\")\n\t\t\t\t\t.selectAll()\n\t\t\t\t\t.orderBy(\"collection_slug\", \"asc\")\n\t\t\t\t\t.orderBy(\"content_id\", \"asc\")\n\t\t\t\t\t.limit(limit),\n\t\t\t)\n\t\t\t.with(\"entry_state\", (db) =>\n\t\t\t\tdb\n\t\t\t\t\t.selectFrom(\"page_groups as page\")\n\t\t\t\t\t.crossJoin(\"_emdash_media_usage_sources as state\")\n\t\t\t\t\t.select([\"page.collection_id\", \"page.collection_slug\", \"page.content_id\"])\n\t\t\t\t\t.select((eb) =>\n\t\t\t\t\t\teb.fn.max<string | null>(\"state.content_deleted_at\").as(\"entry_deleted_at\"),\n\t\t\t\t\t)\n\t\t\t\t\t.whereRef(\"page.collection_slug\", \"=\", \"state.collection_slug\")\n\t\t\t\t\t.whereRef(\"page.content_id\", \"=\", \"state.content_id\")\n\t\t\t\t\t.where(\"state.source_type\", \"=\", \"content\")\n\t\t\t\t\t.where(\"state.source_variant\", \"in\", [\"columns\", \"draft_overlay\"])\n\t\t\t\t\t.where(contentSourceMatchesActiveCollection(\"state\", \"page.collection_id\"))\n\t\t\t\t\t.groupBy([\"page.collection_id\", \"page.collection_slug\", \"page.content_id\"]),\n\t\t\t)\n\t\t\t.selectFrom(\"entry_state as page\")\n\t\t\t.crossJoin(\"_emdash_media_usage_sources as s\")\n\t\t\t.crossJoin(\"_emdash_media_usage as u\")\n\t\t\t.whereRef(\"page.collection_slug\", \"=\", \"s.collection_slug\")\n\t\t\t.whereRef(\"page.content_id\", \"=\", \"s.content_id\")\n\t\t\t.where(contentSourceMatchesActiveCollection(\"s\", \"page.collection_id\"))\n\t\t\t.whereRef(\"s.source_key\", \"=\", \"u.source_key\")\n\t\t\t.whereRef(\"s.current_generation\", \"=\", \"u.generation\")\n\t\t\t.select(currentUsageSelect)\n\t\t\t.select(\"page.entry_deleted_at\")\n\t\t\t.select(\n\t\t\t\tsql<number>`CASE\n\t\t\t\t\tWHEN (SELECT COUNT(*) FROM matched_groups) > ${limit} THEN 1\n\t\t\t\t\tELSE 0\n\t\t\t\tEND`.as(\"has_more\"),\n\t\t\t)\n\t\t\t.where(\"u.media_id\", \"=\", mediaId)\n\t\t\t.where(\"s.source_type\", \"=\", \"content\")\n\t\t\t.where(\"s.collection_slug\", \"is not\", null)\n\t\t\t.where(\"s.content_id\", \"is not\", null)\n\t\t\t.where(\"s.source_variant\", \"in\", [\"columns\", \"draft_overlay\"])\n\t\t\t.where(CONTENT_SOURCE_ELIGIBILITY)\n\t\t\t.orderBy(\"s.collection_slug\", \"asc\")\n\t\t\t.orderBy(\"s.content_id\", \"asc\")\n\t\t\t.orderBy(\"s.source_variant\", \"asc\")\n\t\t\t.orderBy(\"s.source_key\", \"asc\")\n\t\t\t.orderBy(\"u.field_path\", \"asc\")\n\t\t\t.orderBy(\"u.occurrence_index\", \"asc\")\n\t\t\t.orderBy(\"u.id\", \"asc\")\n\t\t\t.execute();\n\n\t\tconst items = groupUsageRows(rows);\n\t\tconst result: FindManyResult<MediaUsageEntryGroup> = { items };\n\t\tif (Number(rows[0]?.has_more ?? 0) === 1 && items.length > 0) {\n\t\t\tconst last = items.at(-1)!;\n\t\t\tresult.nextCursor = encodeCursor(last.collectionSlug, last.contentId);\n\t\t}\n\t\treturn result;\n\t}\n\n\tasync findCurrentUsageByMediaId(mediaId: string): Promise<MediaUsageRecord[]> {\n\t\tconst rows = await this.db\n\t\t\t.selectFrom(\"_emdash_media_usage_sources as s\")\n\t\t\t.innerJoin(\"_emdash_media_usage as u\", (join) =>\n\t\t\t\tjoin\n\t\t\t\t\t.onRef(\"u.source_key\", \"=\", \"s.source_key\")\n\t\t\t\t\t.onRef(\"u.generation\", \"=\", \"s.current_generation\"),\n\t\t\t)\n\t\t\t.select(currentUsageSelect)\n\t\t\t.where(\"u.media_id\", \"=\", mediaId)\n\t\t\t.orderBy(\"s.source_key\", \"asc\")\n\t\t\t.orderBy(\"u.field_path\", \"asc\")\n\t\t\t.orderBy(\"u.occurrence_index\", \"asc\")\n\t\t\t.execute();\n\n\t\treturn rows.map(rowToUsageRecord);\n\t}\n\n\tasync findCurrentUsageByProviderAsset(\n\t\tprovider: string,\n\t\tproviderAssetId: string,\n\t): Promise<MediaUsageRecord[]> {\n\t\tconst rows = await this.db\n\t\t\t.selectFrom(\"_emdash_media_usage_sources as s\")\n\t\t\t.innerJoin(\"_emdash_media_usage as u\", (join) =>\n\t\t\t\tjoin\n\t\t\t\t\t.onRef(\"u.source_key\", \"=\", \"s.source_key\")\n\t\t\t\t\t.onRef(\"u.generation\", \"=\", \"s.current_generation\"),\n\t\t\t)\n\t\t\t.select(currentUsageSelect)\n\t\t\t.where(\"u.provider\", \"=\", provider)\n\t\t\t.where(\"u.provider_asset_id\", \"=\", providerAssetId)\n\t\t\t.orderBy(\"s.source_key\", \"asc\")\n\t\t\t.orderBy(\"u.field_path\", \"asc\")\n\t\t\t.orderBy(\"u.occurrence_index\", \"asc\")\n\t\t\t.execute();\n\n\t\treturn rows.map(rowToUsageRecord);\n\t}\n\n\tasync findCurrentUsagePageByMediaId(\n\t\tmediaId: string,\n\t\toptions: FindMediaUsageOptions = {},\n\t): Promise<FindManyResult<MediaUsageRecord>> {\n\t\treturn this.findCurrentUsagePage((query) => query.where(\"u.media_id\", \"=\", mediaId), options);\n\t}\n\n\tasync findCurrentUsagePageByProviderAsset(\n\t\tprovider: string,\n\t\tproviderAssetId: string,\n\t\toptions: FindMediaUsageOptions = {},\n\t): Promise<FindManyResult<MediaUsageRecord>> {\n\t\treturn this.findCurrentUsagePage(\n\t\t\t(query) =>\n\t\t\t\tquery.where(\"u.provider\", \"=\", provider).where(\"u.provider_asset_id\", \"=\", providerAssetId),\n\t\t\toptions,\n\t\t);\n\t}\n\n\tasync deleteSource(sourceKey: string): Promise<number> {\n\t\treturn this.deleteSources([sourceKey]);\n\t}\n\n\tasync deleteSourceIfCurrent(\n\t\tsourceKey: string,\n\t\texpectedCurrentGeneration: string,\n\t): Promise<MediaUsageGuardedDeleteResult> {\n\t\tlet deleted = false;\n\t\tawait withTransaction(this.db, async (trx) => {\n\t\t\tawait this.lockCleanupBeforeSourceDelete(trx);\n\t\t\tconst result = await trx\n\t\t\t\t.deleteFrom(\"_emdash_media_usage_sources\")\n\t\t\t\t.where(\"source_key\", \"=\", sourceKey)\n\t\t\t\t.where(\"current_generation\", \"=\", expectedCurrentGeneration)\n\t\t\t\t.executeTakeFirst();\n\t\t\tdeleted = Number(result.numDeletedRows ?? 0) > 0;\n\t\t\tif (!deleted) return;\n\t\t\tawait this.deleteSourceGenerationOccurrences(trx, sourceKey, expectedCurrentGeneration);\n\t\t});\n\n\t\treturn {\n\t\t\tdeleted,\n\t\t\tsource: await this.findSource(sourceKey),\n\t\t};\n\t}\n\n\tasync deleteSourceIfMatching(\n\t\tsourceKey: string,\n\t\texpectedSource: MediaUsageSource,\n\t): Promise<MediaUsageGuardedDeleteResult> {\n\t\tlet deleted = false;\n\t\tawait withTransaction(this.db, async (trx) => {\n\t\t\tawait this.lockCleanupBeforeSourceDelete(trx);\n\t\t\tconst result = await trx\n\t\t\t\t.deleteFrom(\"_emdash_media_usage_sources\")\n\t\t\t\t.where(\"source_key\", \"=\", sourceKey)\n\t\t\t\t.where(this.sourceMatchExpression(expectedSource))\n\t\t\t\t.where(\n\t\t\t\t\tthis.currentCollectionExists(expectedSource.collectionId, expectedSource.collectionSlug),\n\t\t\t\t)\n\t\t\t\t.executeTakeFirst();\n\t\t\tdeleted = Number(result.numDeletedRows ?? 0) > 0;\n\t\t\tif (!deleted) return;\n\t\t\tawait this.deleteSourceGenerationOccurrences(\n\t\t\t\ttrx,\n\t\t\t\tsourceKey,\n\t\t\t\texpectedSource.currentGeneration,\n\t\t\t);\n\t\t});\n\n\t\treturn {\n\t\t\tdeleted,\n\t\t\tsource: await this.findSource(sourceKey),\n\t\t};\n\t}\n\n\tasync deleteSourceIfMatchingContentAbsent(\n\t\tsourceKey: string,\n\t\texpectedSource: MediaUsageSource,\n\t\tcollectionSlug: string,\n\t\tcontentId: string,\n\t): Promise<MediaUsageGuardedAbsentDeleteResult> {\n\t\tvalidateIdentifier(collectionSlug, \"collection slug\");\n\t\tconst tableName = `ec_${collectionSlug}`;\n\t\tlet deleted = false;\n\t\tawait withTransaction(this.db, async (trx) => {\n\t\t\tawait this.lockCleanupBeforeSourceDelete(trx);\n\t\t\tconst result = await trx\n\t\t\t\t.deleteFrom(\"_emdash_media_usage_sources\")\n\t\t\t\t.where(\"source_key\", \"=\", sourceKey)\n\t\t\t\t.where(this.sourceMatchExpression(expectedSource))\n\t\t\t\t.where(\n\t\t\t\t\tthis.currentCollectionExists(expectedSource.collectionId, expectedSource.collectionSlug),\n\t\t\t\t)\n\t\t\t\t.where(\n\t\t\t\t\tsql<boolean>`NOT EXISTS (SELECT 1 FROM ${sql.ref(tableName)} WHERE id = ${contentId})`,\n\t\t\t\t)\n\t\t\t\t.executeTakeFirst();\n\t\t\tdeleted = Number(result.numDeletedRows ?? 0) > 0;\n\t\t\tif (!deleted) return;\n\t\t\tawait this.deleteSourceGenerationOccurrences(\n\t\t\t\ttrx,\n\t\t\t\tsourceKey,\n\t\t\t\texpectedSource.currentGeneration,\n\t\t\t);\n\t\t});\n\t\tconst contentPresent = deleted ? false : await this.contentRowExists(tableName, contentId);\n\n\t\treturn {\n\t\t\tdeleted,\n\t\t\tcontentPresent,\n\t\t\tsource: deleted || contentPresent ? null : await this.findSource(sourceKey),\n\t\t};\n\t}\n\n\tasync deleteSources(sourceKeys: readonly string[]): Promise<number> {\n\t\treturn this.deleteSourceKeys(sourceKeys);\n\t}\n\n\tasync deleteContentSources(collectionSlug: string, contentId: string): Promise<number> {\n\t\tconst sourceRows = await this.db\n\t\t\t.selectFrom(\"_emdash_media_usage_sources\")\n\t\t\t.select(\"source_key\")\n\t\t\t.where(\"source_type\", \"=\", \"content\")\n\t\t\t.where(\"collection_slug\", \"=\", collectionSlug)\n\t\t\t.where(\"content_id\", \"=\", contentId)\n\t\t\t.execute();\n\t\tconst sourceKeys = sourceRows.map((row) => row.source_key);\n\t\treturn this.deleteSourceKeys(sourceKeys);\n\t}\n\n\tasync deleteCollectionSources(collectionSlug: string): Promise<number> {\n\t\tlet deleted = 0;\n\t\twhile (true) {\n\t\t\tconst sourceRows = await this.db\n\t\t\t\t.selectFrom(\"_emdash_media_usage_sources\")\n\t\t\t\t.select(\"source_key\")\n\t\t\t\t.where(\"source_type\", \"=\", \"content\")\n\t\t\t\t.where(\"collection_slug\", \"=\", collectionSlug)\n\t\t\t\t.orderBy(\"source_key\", \"asc\")\n\t\t\t\t.limit(SQL_BATCH_SIZE)\n\t\t\t\t.execute();\n\t\t\tif (sourceRows.length === 0) break;\n\n\t\t\tdeleted += await this.deleteSourceKeys(sourceRows.map((row) => row.source_key));\n\t\t}\n\t\treturn deleted;\n\t}\n\n\tasync findCollectionContentSources(\n\t\tcollectionSlug: string,\n\t\tcollectionId?: string,\n\t): Promise<MediaUsageSource[]> {\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"_emdash_media_usage_sources\")\n\t\t\t.selectAll()\n\t\t\t.where(\"source_type\", \"=\", \"content\")\n\t\t\t.where(\"collection_slug\", \"=\", collectionSlug)\n\t\t\t.orderBy(\"source_key\", \"asc\");\n\t\tif (collectionId !== undefined) query = query.where(\"collection_id\", \"=\", collectionId);\n\t\tconst rows = await query.execute();\n\t\treturn rows.map((row) => rowToSource(row));\n\t}\n\n\tasync claimMediaUsageCleanup(input: {\n\t\tleaseToken: string;\n\t\tleaseDurationSeconds: number;\n\t\tnextEligibleDelaySeconds: number;\n\t\tsweepSafetyWindowSeconds: number;\n\t}): Promise<MediaUsageCleanupClaim | null> {\n\t\tconst leaseDurationSeconds = cleanupDurationSeconds(input.leaseDurationSeconds);\n\t\tconst nextEligibleDelaySeconds = cleanupDurationSeconds(input.nextEligibleDelaySeconds);\n\t\tconst sweepSafetyWindowSeconds = cleanupDurationSeconds(input.sweepSafetyWindowSeconds);\n\t\tconst claimedAt = this.cleanupTimestampOffset(0);\n\t\tconst leaseExpiresAt = this.cleanupTimestampOffset(leaseDurationSeconds);\n\t\tconst nextEligibleAt = this.cleanupTimestampOffset(nextEligibleDelaySeconds);\n\t\tconst sweepBeforeAt = this.cleanupTimestampOffset(-sweepSafetyWindowSeconds);\n\t\tconst row = await this.db\n\t\t\t.updateTable(\"_emdash_media_usage_cleanup\")\n\t\t\t.set({\n\t\t\t\tlease_token: input.leaseToken,\n\t\t\t\tlease_expires_at: leaseExpiresAt,\n\t\t\t\tnext_eligible_at: nextEligibleAt,\n\t\t\t\tlast_started_at: claimedAt,\n\t\t\t\tupdated_at: claimedAt,\n\t\t\t\tscan_before_at: sql<string>`CASE\n\t\t\t\t\tWHEN scan_before_at IS NULL THEN ${sweepBeforeAt}\n\t\t\t\t\tELSE scan_before_at\n\t\t\t\tEND`,\n\t\t\t})\n\t\t\t.where(\"task_key\", \"=\", \"projection_gc\")\n\t\t\t.where(this.cleanupTimestampIsDue(\"next_eligible_at\"))\n\t\t\t.where((eb) =>\n\t\t\t\teb.or([eb(\"lease_token\", \"is\", null), this.cleanupTimestampIsDue(\"lease_expires_at\")]),\n\t\t\t)\n\t\t\t.returning([\n\t\t\t\t\"cursor_created_at\",\n\t\t\t\t\"cursor_id\",\n\t\t\t\t\"last_started_at\",\n\t\t\t\t\"scan_before_at\",\n\t\t\t\t\"consecutive_failures\",\n\t\t\t])\n\t\t\t.executeTakeFirst();\n\t\tif (!row) return null;\n\t\tif (!row.last_started_at || !row.scan_before_at) {\n\t\t\tthrow new Error(\"Media usage cleanup claim did not persist its database timestamps\");\n\t\t}\n\t\treturn {\n\t\t\tleaseToken: input.leaseToken,\n\t\t\tcursor:\n\t\t\t\trow.cursor_created_at && row.cursor_id\n\t\t\t\t\t? { createdAt: row.cursor_created_at, id: row.cursor_id }\n\t\t\t\t\t: null,\n\t\t\tclaimedAt: row.last_started_at,\n\t\t\tscanBeforeAt: row.scan_before_at,\n\t\t\tconsecutiveFailures: row.consecutive_failures,\n\t\t};\n\t}\n\n\tasync findMediaUsageCleanupCandidates(input: {\n\t\tcutoff: string;\n\t\tcursor: MediaUsageCleanupCursor | null;\n\t\tlimit: number;\n\t\tcleanupLease?: MediaUsageCleanupLease;\n\t}): Promise<MediaUsageCleanupCandidate[]> {\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"_emdash_media_usage as u\")\n\t\t\t.leftJoin(\"_emdash_media_usage_sources as s\", \"s.source_key\", \"u.source_key\")\n\t\t\t.leftJoin(\"_emdash_media_usage_generation_writes as writer\", (join) =>\n\t\t\t\tjoin\n\t\t\t\t\t.onRef(\"writer.source_key\", \"=\", \"u.source_key\")\n\t\t\t\t\t.onRef(\"writer.generation\", \"=\", \"u.generation\"),\n\t\t\t)\n\t\t\t.select([\n\t\t\t\t\"u.id as id\",\n\t\t\t\t\"u.source_key as source_key\",\n\t\t\t\t\"u.generation as generation\",\n\t\t\t\t\"u.created_at as created_at\",\n\t\t\t\t\"s.current_generation as current_generation\",\n\t\t\t\t\"s.indexed_at as indexed_at\",\n\t\t\t\t\"writer.expires_at as write_lease_expires_at\",\n\t\t\t])\n\t\t\t.where(\"u.created_at\", \"<\", input.cutoff)\n\t\t\t.orderBy(\"u.created_at\", \"asc\")\n\t\t\t.orderBy(\"u.id\", \"asc\")\n\t\t\t.limit(Math.max(0, Math.floor(input.limit)));\n\t\tif (input.cleanupLease) {\n\t\t\tquery = query.where(this.activeCleanupLeaseExpression(input.cleanupLease));\n\t\t}\n\n\t\tif (input.cursor) {\n\t\t\tquery = query.where((eb) =>\n\t\t\t\teb.or([\n\t\t\t\t\teb(\"u.created_at\", \">\", input.cursor!.createdAt),\n\t\t\t\t\teb.and([\n\t\t\t\t\t\teb(\"u.created_at\", \"=\", input.cursor!.createdAt),\n\t\t\t\t\t\teb(\"u.id\", \">\", input.cursor!.id),\n\t\t\t\t\t]),\n\t\t\t\t]),\n\t\t\t);\n\t\t}\n\n\t\tconst rows = await query.execute();\n\t\treturn rows.map((row) => ({\n\t\t\tid: row.id,\n\t\t\tsourceKey: row.source_key,\n\t\t\tgeneration: row.generation,\n\t\t\tcreatedAt: row.created_at,\n\t\t\tcurrentGeneration: row.current_generation,\n\t\t\tindexedAt: row.indexed_at,\n\t\t\twriteLeaseExpiresAt: row.write_lease_expires_at,\n\t\t}));\n\t}\n\n\tasync completeMediaUsageCleanup(input: MediaUsageCleanupCompletion): Promise<boolean> {\n\t\tconst updates = {\n\t\t\tlease_token: null,\n\t\t\tlease_expires_at: null,\n\t\t\tcursor_created_at: input.sweepComplete ? null : (input.nextCursor?.createdAt ?? null),\n\t\t\tcursor_id: input.sweepComplete ? null : (input.nextCursor?.id ?? null),\n\t\t\t...(input.sweepComplete ? { scan_before_at: null } : {}),\n\t\t\tconsecutive_failures: 0,\n\t\t\tlast_completed_at: this.cleanupTimestampOffset(0),\n\t\t\tlast_candidate_count: input.candidateCount,\n\t\t\tlast_deleted_orphans: input.deletedOrphans,\n\t\t\tlast_deleted_stale: input.deletedStale,\n\t\t\tlast_deleted_abandoned: input.deletedAbandoned,\n\t\t\tlast_deleted_write_leases: input.deletedWriteLeases,\n\t\t\tlast_backlog_lower_bound: input.backlogLowerBound,\n\t\t\tlast_scan_has_more: input.scanHasMore ? 1 : 0,\n\t\t\tlast_duration_ms: input.durationMs,\n\t\t\tlast_error_code: null,\n\t\t\tupdated_at: this.cleanupTimestampOffset(0),\n\t\t};\n\t\tconst result = await this.db\n\t\t\t.updateTable(\"_emdash_media_usage_cleanup\")\n\t\t\t.set(updates)\n\t\t\t.where(\"task_key\", \"=\", \"projection_gc\")\n\t\t\t.where(\"lease_token\", \"=\", input.leaseToken)\n\t\t\t.where(this.cleanupLeaseExpiryIsInFuture(\"_emdash_media_usage_cleanup.lease_expires_at\"))\n\t\t\t.executeTakeFirst();\n\t\treturn Number(result.numUpdatedRows ?? 0) > 0;\n\t}\n\n\tasync failMediaUsageCleanup(input: {\n\t\tleaseToken: string;\n\t\tretryDelaySeconds: number;\n\t\tconsecutiveFailures: number;\n\t\tdurationMs: number;\n\t\terrorCode: string;\n\t}): Promise<boolean> {\n\t\tconst retryDelaySeconds = cleanupDurationSeconds(input.retryDelaySeconds);\n\t\tconst result = await this.db\n\t\t\t.updateTable(\"_emdash_media_usage_cleanup\")\n\t\t\t.set({\n\t\t\t\tlease_token: null,\n\t\t\t\tlease_expires_at: null,\n\t\t\t\tnext_eligible_at: this.cleanupTimestampOffset(retryDelaySeconds),\n\t\t\t\tconsecutive_failures: input.consecutiveFailures,\n\t\t\t\tlast_completed_at: this.cleanupTimestampOffset(0),\n\t\t\t\tlast_duration_ms: input.durationMs,\n\t\t\t\tlast_error_code: input.errorCode,\n\t\t\t\tupdated_at: this.cleanupTimestampOffset(0),\n\t\t\t})\n\t\t\t.where(\"task_key\", \"=\", \"projection_gc\")\n\t\t\t.where(\"lease_token\", \"=\", input.leaseToken)\n\t\t\t.where(this.cleanupLeaseExpiryIsInFuture(\"_emdash_media_usage_cleanup.lease_expires_at\"))\n\t\t\t.executeTakeFirst();\n\t\treturn Number(result.numUpdatedRows ?? 0) > 0;\n\t}\n\n\tasync deleteOrphanOccurrencesOlderThan(\n\t\tcutoff: string,\n\t\tlimit: number,\n\t\toptions: MediaUsageCleanupDeleteOptions = {},\n\t): Promise<number> {\n\t\tconst batchLimit = Math.floor(limit);\n\t\tif (batchLimit <= 0) return 0;\n\t\tif (options.candidateIds) {\n\t\t\treturn this.deleteOrphanCandidateIds(\n\t\t\t\toptions.candidateIds.slice(0, batchLimit),\n\t\t\t\tcutoff,\n\t\t\t\toptions.cleanupLease,\n\t\t\t\toptions.canIssueStatement,\n\t\t\t);\n\t\t}\n\t\tif (!canIssueCleanupStatement(options.canIssueStatement)) return 0;\n\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"_emdash_media_usage as u\")\n\t\t\t.leftJoin(\"_emdash_media_usage_sources as s\", (join) =>\n\t\t\t\tjoin.onRef(\"s.source_key\", \"=\", \"u.source_key\"),\n\t\t\t)\n\t\t\t.leftJoin(\"_emdash_media_usage_generation_writes as writer\", (join) =>\n\t\t\t\tjoin\n\t\t\t\t\t.onRef(\"writer.source_key\", \"=\", \"u.source_key\")\n\t\t\t\t\t.onRef(\"writer.generation\", \"=\", \"u.generation\"),\n\t\t\t)\n\t\t\t.select(\"u.id\")\n\t\t\t.where(\"s.source_key\", \"is\", null)\n\t\t\t.where(\"u.created_at\", \"<\", cutoff)\n\t\t\t.where(this.noActiveGenerationWriteExpression(\"u\"))\n\t\t\t.orderBy(\"u.created_at\", \"asc\")\n\t\t\t.orderBy(\"u.id\", \"asc\")\n\t\t\t.limit(batchLimit);\n\t\tif (options.cleanupLease) {\n\t\t\tquery = query.where(this.activeCleanupLeaseExpression(options.cleanupLease));\n\t\t}\n\t\tconst rows = await query.execute();\n\n\t\treturn this.deleteOrphanCandidateIds(\n\t\t\trows.map((row) => row.id),\n\t\t\tcutoff,\n\t\t\toptions.cleanupLease,\n\t\t\toptions.canIssueStatement,\n\t\t);\n\t}\n\n\tasync deleteStaleGenerationsOlderThan(\n\t\tcutoff: string,\n\t\tlimit: number,\n\t\toptions: MediaUsageCleanupDeleteOptions = {},\n\t): Promise<number> {\n\t\tconst batchLimit = Math.floor(limit);\n\t\tif (batchLimit <= 0) return 0;\n\t\tif (options.candidateIds) {\n\t\t\treturn this.deleteStaleCandidateIds(\n\t\t\t\toptions.candidateIds.slice(0, batchLimit),\n\t\t\t\tcutoff,\n\t\t\t\toptions.cleanupLease,\n\t\t\t\toptions.canIssueStatement,\n\t\t\t);\n\t\t}\n\t\tif (!canIssueCleanupStatement(options.canIssueStatement)) return 0;\n\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"_emdash_media_usage as u\")\n\t\t\t.innerJoin(\"_emdash_media_usage_sources as s\", (join) =>\n\t\t\t\tjoin.onRef(\"s.source_key\", \"=\", \"u.source_key\"),\n\t\t\t)\n\t\t\t.leftJoin(\"_emdash_media_usage_generation_writes as writer\", (join) =>\n\t\t\t\tjoin\n\t\t\t\t\t.onRef(\"writer.source_key\", \"=\", \"u.source_key\")\n\t\t\t\t\t.onRef(\"writer.generation\", \"=\", \"u.generation\"),\n\t\t\t)\n\t\t\t.select(\"u.id\")\n\t\t\t.where(\"u.created_at\", \"<\", cutoff)\n\t\t\t.whereRef(\"u.generation\", \"!=\", \"s.current_generation\")\n\t\t\t.whereRef(\"u.created_at\", \"<\", \"s.indexed_at\")\n\t\t\t.where(this.noActiveGenerationWriteExpression(\"u\"))\n\t\t\t.orderBy(\"u.created_at\", \"asc\")\n\t\t\t.orderBy(\"u.id\", \"asc\")\n\t\t\t.limit(batchLimit);\n\t\tif (options.cleanupLease) {\n\t\t\tquery = query.where(this.activeCleanupLeaseExpression(options.cleanupLease));\n\t\t}\n\t\tconst rows = await query.execute();\n\n\t\treturn this.deleteStaleCandidateIds(\n\t\t\trows.map((row) => row.id),\n\t\t\tcutoff,\n\t\t\toptions.cleanupLease,\n\t\t\toptions.canIssueStatement,\n\t\t);\n\t}\n\n\tasync deleteAbandonedGenerationsOlderThan(\n\t\tcutoff: string,\n\t\tlimit: number,\n\t\toptions: MediaUsageCleanupDeleteOptions = {},\n\t): Promise<number> {\n\t\tconst batchLimit = Math.floor(limit);\n\t\tif (batchLimit <= 0) return 0;\n\t\tif (options.candidateIds) {\n\t\t\treturn this.deleteAbandonedCandidateIds(\n\t\t\t\toptions.candidateIds.slice(0, batchLimit),\n\t\t\t\tcutoff,\n\t\t\t\toptions.cleanupLease,\n\t\t\t\toptions.canIssueStatement,\n\t\t\t);\n\t\t}\n\t\tif (!canIssueCleanupStatement(options.canIssueStatement)) return 0;\n\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"_emdash_media_usage as u\")\n\t\t\t.innerJoin(\"_emdash_media_usage_sources as s\", (join) =>\n\t\t\t\tjoin.onRef(\"s.source_key\", \"=\", \"u.source_key\"),\n\t\t\t)\n\t\t\t.leftJoin(\"_emdash_media_usage_generation_writes as writer\", (join) =>\n\t\t\t\tjoin\n\t\t\t\t\t.onRef(\"writer.source_key\", \"=\", \"u.source_key\")\n\t\t\t\t\t.onRef(\"writer.generation\", \"=\", \"u.generation\"),\n\t\t\t)\n\t\t\t.select(\"u.id\")\n\t\t\t.where(\"u.created_at\", \"<\", cutoff)\n\t\t\t.whereRef(\"u.generation\", \"!=\", \"s.current_generation\")\n\t\t\t.whereRef(\"u.created_at\", \">=\", \"s.indexed_at\")\n\t\t\t.where(this.noActiveGenerationWriteExpression(\"u\"))\n\t\t\t.orderBy(\"u.created_at\", \"asc\")\n\t\t\t.orderBy(\"u.id\", \"asc\")\n\t\t\t.limit(batchLimit);\n\t\tif (options.cleanupLease) {\n\t\t\tquery = query.where(this.activeCleanupLeaseExpression(options.cleanupLease));\n\t\t}\n\t\tconst rows = await query.execute();\n\n\t\treturn this.deleteAbandonedCandidateIds(\n\t\t\trows.map((row) => row.id),\n\t\t\tcutoff,\n\t\t\toptions.cleanupLease,\n\t\t\toptions.canIssueStatement,\n\t\t);\n\t}\n\n\tasync deleteExpiredGenerationWriteLeases(\n\t\tlimit: number,\n\t\tcleanupLease?: MediaUsageCleanupLease,\n\t\tcanIssueStatement?: () => boolean,\n\t): Promise<number> {\n\t\tconst batchLimit = Math.floor(limit);\n\t\tif (batchLimit <= 0 || !canIssueCleanupStatement(canIssueStatement)) return 0;\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"_emdash_media_usage_generation_writes\")\n\t\t\t.select(\"lease_token\")\n\t\t\t.where(this.generationWriteLeaseHasExpired(\"expires_at\"))\n\t\t\t.orderBy(\"expires_at\", \"asc\")\n\t\t\t.orderBy(\"lease_token\", \"asc\")\n\t\t\t.limit(batchLimit);\n\t\tif (cleanupLease) query = query.where(this.activeCleanupLeaseExpression(cleanupLease));\n\t\tconst rows = await query.execute();\n\t\tif (rows.length === 0 || !canIssueCleanupStatement(canIssueStatement)) return 0;\n\t\tlet deleteQuery = this.db\n\t\t\t.deleteFrom(\"_emdash_media_usage_generation_writes\")\n\t\t\t.where(\n\t\t\t\t\"lease_token\",\n\t\t\t\t\"in\",\n\t\t\t\trows.map((row) => row.lease_token),\n\t\t\t)\n\t\t\t.where(this.generationWriteLeaseHasExpired(\"expires_at\"));\n\t\tif (cleanupLease)\n\t\t\tdeleteQuery = deleteQuery.where(this.activeCleanupLeaseExpression(cleanupLease));\n\t\tconst result = await deleteQuery.executeTakeFirst();\n\t\treturn Number(result.numDeletedRows ?? 0);\n\t}\n\n\tasync upsertIndexStatus(input: MediaUsageIndexStatusInput): Promise<MediaUsageIndexStatus> {\n\t\tconst now = input.updatedAt ?? new Date().toISOString();\n\t\tconst row = {\n\t\t\tadapter_id: input.adapterId,\n\t\t\tscope_type: input.scopeType,\n\t\t\tscope_key: input.scopeKey,\n\t\t\tstatus: input.status,\n\t\t\tschema_version: input.schemaVersion ?? 1,\n\t\t\tstarted_at: input.startedAt ?? null,\n\t\t\tcompleted_at: input.completedAt ?? null,\n\t\t\tcursor: input.cursor ?? null,\n\t\t\tindexed_source_count: input.indexedSourceCount ?? 0,\n\t\t\tfailed_source_count: input.failedSourceCount ?? 0,\n\t\t\tlast_error_code: input.lastErrorCode ?? null,\n\t\t\tupdated_at: now,\n\t\t};\n\n\t\tawait this.db\n\t\t\t.insertInto(\"_emdash_media_usage_index_status\")\n\t\t\t.values(row)\n\t\t\t.onConflict((oc) =>\n\t\t\t\toc.columns([\"adapter_id\", \"scope_type\", \"scope_key\"]).doUpdateSet({\n\t\t\t\t\tstatus: row.status,\n\t\t\t\t\tschema_version: row.schema_version,\n\t\t\t\t\tstarted_at: row.started_at,\n\t\t\t\t\tcompleted_at: row.completed_at,\n\t\t\t\t\tcursor: row.cursor,\n\t\t\t\t\tindexed_source_count: row.indexed_source_count,\n\t\t\t\t\tfailed_source_count: row.failed_source_count,\n\t\t\t\t\tlast_error_code: row.last_error_code,\n\t\t\t\t\tupdated_at: row.updated_at,\n\t\t\t\t}),\n\t\t\t)\n\t\t\t.execute();\n\n\t\tconst status = await this.findIndexStatus(input);\n\t\tif (!status) {\n\t\t\tthrow new Error(\n\t\t\t\t`Media usage index status ${input.adapterId}:${input.scopeType}:${input.scopeKey} was not persisted`,\n\t\t\t);\n\t\t}\n\t\treturn status;\n\t}\n\n\tasync invalidateIndexStatusForSchemaChange(collectionSlug: string): Promise<boolean> {\n\t\tconst result = await this.db\n\t\t\t.updateTable(\"_emdash_media_usage_index_status as status\")\n\t\t\t.set({\n\t\t\t\tchange_epoch: sql<number>`change_epoch + 1`,\n\t\t\t\tstatus: \"stale\",\n\t\t\t\tcompleted_at: null,\n\t\t\t\tcursor: null,\n\t\t\t\tlast_error_code: \"CONTENT_USAGE_STALE\",\n\t\t\t\treconciliation_required: 1,\n\t\t\t\tupdated_at: this.sortableUtcTimestamp(),\n\t\t\t})\n\t\t\t.where(\"status.adapter_id\", \"=\", \"content-media\")\n\t\t\t.where(\"status.scope_type\", \"=\", \"collection\")\n\t\t\t.where(\"status.scope_key\", \"=\", collectionSlug)\n\t\t\t.where(\"status.capture_state\", \"=\", \"active\")\n\t\t\t.where((eb) =>\n\t\t\t\teb.exists(\n\t\t\t\t\teb\n\t\t\t\t\t\t.selectFrom(\"_emdash_collections as collection\")\n\t\t\t\t\t\t.select(\"collection.id\")\n\t\t\t\t\t\t.whereRef(\"collection.id\", \"=\", \"status.collection_id\")\n\t\t\t\t\t\t.whereRef(\"collection.slug\", \"=\", \"status.scope_key\"),\n\t\t\t\t),\n\t\t\t)\n\t\t\t.where(\n\t\t\t\tsql<boolean>`EXISTS (\n\t\t\t\t\tSELECT 1\n\t\t\t\t\tFROM _emdash_media_usage_activation AS activation\n\t\t\t\t\tWHERE activation.task_key = 'incremental_capture'\n\t\t\t\t\t\tAND activation.state = 'active'\n\t\t\t\t)`,\n\t\t\t)\n\t\t\t.executeTakeFirst();\n\t\treturn Number(result.numUpdatedRows ?? 0) === 1;\n\t}\n\n\tasync beginIndexStatusRepair(\n\t\tinput: MediaUsageIndexStatusRepairInput,\n\t): Promise<MediaUsageIndexStatus> {\n\t\treturn this.upsertIndexStatus({\n\t\t\tadapterId: input.adapterId,\n\t\t\tscopeType: input.scopeType,\n\t\t\tscopeKey: input.scopeKey,\n\t\t\tstatus: \"running\",\n\t\t\tschemaVersion: input.schemaVersion,\n\t\t\tstartedAt: input.startedAt,\n\t\t\tcompletedAt: null,\n\t\t\tcursor: input.runToken,\n\t\t\tindexedSourceCount: 0,\n\t\t\tfailedSourceCount: 0,\n\t\t\tlastErrorCode: null,\n\t\t\tupdatedAt: input.updatedAt,\n\t\t});\n\t}\n\n\tasync finalizeIndexStatusRepairIfRunning(\n\t\tinput: MediaUsageIndexStatusFinalizeInput,\n\t): Promise<MediaUsageGuardedIndexStatusResult> {\n\t\tconst updates: Updateable<MediaUsageIndexStatusTable> = {\n\t\t\tstatus: input.status,\n\t\t\tcompleted_at: input.completedAt,\n\t\t\tcursor: null,\n\t\t\tindexed_source_count: input.indexedSourceCount ?? 0,\n\t\t\tfailed_source_count: input.failedSourceCount ?? 0,\n\t\t\tlast_error_code: input.lastErrorCode ?? null,\n\t\t\tupdated_at: input.updatedAt ?? new Date().toISOString(),\n\t\t};\n\t\tif (input.schemaVersion !== undefined) updates.schema_version = input.schemaVersion;\n\n\t\tconst result = await this.db\n\t\t\t.updateTable(\"_emdash_media_usage_index_status\")\n\t\t\t.set(updates)\n\t\t\t.where(\"adapter_id\", \"=\", input.adapterId)\n\t\t\t.where(\"scope_type\", \"=\", input.scopeType)\n\t\t\t.where(\"scope_key\", \"=\", input.scopeKey)\n\t\t\t.where(\"status\", \"=\", \"running\")\n\t\t\t.where(\"cursor\", \"=\", input.runToken)\n\t\t\t.executeTakeFirst();\n\t\tconst finalized = Number(result.numUpdatedRows ?? 0) > 0;\n\n\t\treturn {\n\t\t\tfinalized,\n\t\t\tstatus: await this.findIndexStatus(input),\n\t\t};\n\t}\n\n\tasync beginIndexStatusRepairAtCurrentEpoch(\n\t\tinput: MediaUsageIndexStatusEpochRepairInput,\n\t): Promise<MediaUsageIndexStatusEpochRepairRun | null> {\n\t\tconst now = this.sortableUtcTimestamp();\n\t\tconst row = await this.db\n\t\t\t.updateTable(\"_emdash_media_usage_index_status\")\n\t\t\t.set({\n\t\t\t\tstatus: \"running\",\n\t\t\t\tschema_version: input.schemaVersion,\n\t\t\t\tstarted_at: now,\n\t\t\t\tcompleted_at: null,\n\t\t\t\tcursor: input.runToken,\n\t\t\t\tindexed_source_count: 0,\n\t\t\t\tfailed_source_count: 0,\n\t\t\t\tlast_error_code: null,\n\t\t\t\treconciliation_required: 1,\n\t\t\t\tupdated_at: now,\n\t\t\t})\n\t\t\t.where(\"adapter_id\", \"=\", input.adapterId)\n\t\t\t.where(\"scope_type\", \"=\", input.scopeType)\n\t\t\t.where(\"scope_key\", \"=\", input.scopeKey)\n\t\t\t.where(\"collection_id\", \"=\", input.collectionId)\n\t\t\t.where(\"capture_state\", \"=\", \"active\")\n\t\t\t.where(\n\t\t\t\tsql<boolean>`EXISTS (\n\t\t\t\t\tSELECT 1\n\t\t\t\t\tFROM _emdash_collections AS collection\n\t\t\t\t\tWHERE collection.id = ${input.collectionId}\n\t\t\t\t\t\tAND collection.slug = ${input.scopeKey}\n\t\t\t\t)`,\n\t\t\t)\n\t\t\t.where(\n\t\t\t\tsql<boolean>`EXISTS (\n\t\t\t\t\tSELECT 1\n\t\t\t\t\tFROM _emdash_media_usage_activation AS activation\n\t\t\t\t\tWHERE activation.task_key = 'incremental_capture'\n\t\t\t\t\t\tAND activation.state = 'active'\n\t\t\t\t)`,\n\t\t\t)\n\t\t\t.returning([\"change_epoch\", \"started_at\"])\n\t\t\t.executeTakeFirst();\n\t\tif (!row?.started_at) return null;\n\t\treturn { changeEpoch: row.change_epoch, startedAt: row.started_at };\n\t}\n\n\tasync finalizeIndexStatusRepairAtEpoch(\n\t\tinput: MediaUsageIndexStatusEpochFinalizeInput,\n\t): Promise<MediaUsageGuardedIndexStatusResult> {\n\t\tconst now = this.sortableUtcTimestamp();\n\t\tconst updates = {\n\t\t\tstatus: input.status,\n\t\t\tschema_version: input.schemaVersion,\n\t\t\tcompleted_at: now,\n\t\t\tcursor: null,\n\t\t\tindexed_source_count: input.indexedSourceCount,\n\t\t\tfailed_source_count: input.failedSourceCount,\n\t\t\tlast_error_code: input.lastErrorCode,\n\t\t\treconciliation_required: input.status === \"complete\" ? 0 : 1,\n\t\t\tupdated_at: now,\n\t\t};\n\n\t\tlet query = this.db\n\t\t\t.updateTable(\"_emdash_media_usage_index_status\")\n\t\t\t.set(updates)\n\t\t\t.where(\"adapter_id\", \"=\", input.adapterId)\n\t\t\t.where(\"scope_type\", \"=\", input.scopeType)\n\t\t\t.where(\"scope_key\", \"=\", input.scopeKey)\n\t\t\t.where(\"collection_id\", \"=\", input.collectionId)\n\t\t\t.where(\"status\", \"=\", \"running\")\n\t\t\t.where(\"cursor\", \"=\", input.runToken)\n\t\t\t.where(\"change_epoch\", \"=\", input.startingEpoch)\n\t\t\t.where(\n\t\t\t\tsql<boolean>`EXISTS (\n\t\t\t\t\tSELECT 1\n\t\t\t\t\tFROM _emdash_collections AS collection\n\t\t\t\t\tWHERE collection.id = ${input.collectionId}\n\t\t\t\t\t\tAND collection.slug = ${input.scopeKey}\n\t\t\t\t)`,\n\t\t\t);\n\t\tif (input.status === \"complete\") {\n\t\t\tquery = query.where(\n\t\t\t\tsql<boolean>`NOT EXISTS (\n\t\t\t\t\tSELECT 1\n\t\t\t\t\tFROM _emdash_media_usage_work AS work\n\t\t\t\t\tWHERE work.collection_id = ${input.collectionId}\n\t\t\t\t)`,\n\t\t\t);\n\t\t}\n\t\tconst result = await query.executeTakeFirst();\n\t\tconst finalized = Number(result.numUpdatedRows ?? 0) > 0;\n\n\t\tif (!finalized) {\n\t\t\tawait this.db\n\t\t\t\t.updateTable(\"_emdash_media_usage_index_status\")\n\t\t\t\t.set({\n\t\t\t\t\tstatus: \"stale\",\n\t\t\t\t\tcompleted_at: null,\n\t\t\t\t\tcursor: null,\n\t\t\t\t\tlast_error_code: \"CONTENT_USAGE_REPAIR_CONFLICT\",\n\t\t\t\t\treconciliation_required: 1,\n\t\t\t\t\tupdated_at: this.sortableUtcTimestamp(),\n\t\t\t\t})\n\t\t\t\t.where(\"adapter_id\", \"=\", input.adapterId)\n\t\t\t\t.where(\"scope_type\", \"=\", input.scopeType)\n\t\t\t\t.where(\"scope_key\", \"=\", input.scopeKey)\n\t\t\t\t.where(\"collection_id\", \"=\", input.collectionId)\n\t\t\t\t.where(\"status\", \"=\", \"running\")\n\t\t\t\t.where(\"cursor\", \"=\", input.runToken)\n\t\t\t\t.execute();\n\t\t}\n\n\t\treturn {\n\t\t\tfinalized,\n\t\t\tstatus: await this.findIndexStatusForCollection(input, input.collectionId),\n\t\t};\n\t}\n\n\tasync recordIncrementalSuccess(input: MediaUsageIncrementalStatusIdentity): Promise<boolean> {\n\t\tconst observed = await this.db\n\t\t\t.selectFrom(\"_emdash_media_usage_index_status\")\n\t\t\t.select(\"change_epoch\")\n\t\t\t.where(\"adapter_id\", \"=\", \"content-media\")\n\t\t\t.where(\"scope_type\", \"=\", \"collection\")\n\t\t\t.where(\"scope_key\", \"=\", input.collectionSlug)\n\t\t\t.where(\"collection_id\", \"=\", input.collectionId)\n\t\t\t.where(\"capture_state\", \"=\", \"active\")\n\t\t\t.where(\n\t\t\t\tsql<boolean>`EXISTS (\n\t\t\t\t\tSELECT 1\n\t\t\t\t\tFROM _emdash_collections AS collection\n\t\t\t\t\tWHERE collection.id = ${input.collectionId}\n\t\t\t\t\t\tAND collection.slug = ${input.collectionSlug}\n\t\t\t\t)`,\n\t\t\t)\n\t\t\t.executeTakeFirst();\n\t\tif (!observed) return false;\n\n\t\tconst canComplete = sql<boolean>`(\n\t\t\treconciliation_required = 0\n\t\t\tAND status IN ('complete', 'stale', 'partial')\n\t\t\tAND NOT EXISTS (\n\t\t\t\tSELECT 1\n\t\t\t\tFROM _emdash_media_usage_work AS work\n\t\t\t\tWHERE work.collection_id = ${input.collectionId}\n\t\t\t)\n\t\t)`;\n\t\tconst now = this.sortableUtcTimestamp();\n\t\tconst result = await this.db\n\t\t\t.updateTable(\"_emdash_media_usage_index_status\")\n\t\t\t.set({\n\t\t\t\tstatus: sql<string>`CASE WHEN ${canComplete} THEN 'complete' ELSE status END`,\n\t\t\t\tcompleted_at: sql<\n\t\t\t\t\tstring | null\n\t\t\t\t>`CASE WHEN ${canComplete} THEN ${now} ELSE completed_at END`,\n\t\t\t\tlast_error_code: sql<\n\t\t\t\t\tstring | null\n\t\t\t\t>`CASE WHEN ${canComplete} THEN NULL ELSE last_error_code END`,\n\t\t\t\tlast_incremental_success_at: now,\n\t\t\t\tupdated_at: now,\n\t\t\t})\n\t\t\t.where(\"adapter_id\", \"=\", \"content-media\")\n\t\t\t.where(\"scope_type\", \"=\", \"collection\")\n\t\t\t.where(\"scope_key\", \"=\", input.collectionSlug)\n\t\t\t.where(\"collection_id\", \"=\", input.collectionId)\n\t\t\t.where(\"change_epoch\", \"=\", observed.change_epoch)\n\t\t\t.where(\"capture_state\", \"=\", \"active\")\n\t\t\t.where(\n\t\t\t\tsql<boolean>`EXISTS (\n\t\t\t\t\tSELECT 1\n\t\t\t\t\tFROM _emdash_collections AS collection\n\t\t\t\t\tWHERE collection.id = ${input.collectionId}\n\t\t\t\t\t\tAND collection.slug = ${input.collectionSlug}\n\t\t\t\t)`,\n\t\t\t)\n\t\t\t.executeTakeFirst();\n\t\treturn Number(result.numUpdatedRows ?? 0) > 0;\n\t}\n\n\tasync recordIncrementalFailure(\n\t\tinput: MediaUsageIncrementalStatusIdentity & {\n\t\t\tcontentId: string;\n\t\t\tworkVersion: number | string;\n\t\t\terrorCode: string;\n\t\t},\n\t): Promise<boolean> {\n\t\tconst now = this.sortableUtcTimestamp();\n\t\tconst automaticRunOwnsCoverage = sql<boolean>`EXISTS (\n\t\t\tSELECT 1\n\t\t\tFROM _emdash_media_usage_reconciliations AS reconciliation\n\t\t\tWHERE reconciliation.collection_id = ${input.collectionId}\n\t\t\t\tAND reconciliation.run_token = cursor\n\t\t)`;\n\t\tconst result = await this.db\n\t\t\t.updateTable(\"_emdash_media_usage_index_status\")\n\t\t\t.set({\n\t\t\t\tstatus: sql<string>`CASE\n\t\t\t\t\tWHEN ${automaticRunOwnsCoverage} THEN status\n\t\t\t\t\tWHEN reconciliation_required = 0 THEN 'partial'\n\t\t\t\t\tWHEN status = 'running' THEN 'stale'\n\t\t\t\t\tELSE status\n\t\t\t\tEND`,\n\t\t\t\tcompleted_at: sql<string | null>`CASE\n\t\t\t\t\tWHEN ${automaticRunOwnsCoverage} THEN completed_at\n\t\t\t\t\tWHEN reconciliation_required = 0 OR status = 'running' THEN NULL\n\t\t\t\t\tELSE completed_at\n\t\t\t\tEND`,\n\t\t\t\tcursor: sql<string | null>`CASE\n\t\t\t\t\tWHEN ${automaticRunOwnsCoverage} THEN cursor\n\t\t\t\t\tWHEN status = 'running' THEN NULL\n\t\t\t\t\tELSE cursor\n\t\t\t\tEND`,\n\t\t\t\tlast_error_code: input.errorCode,\n\t\t\t\tupdated_at: now,\n\t\t\t})\n\t\t\t.where(\"adapter_id\", \"=\", \"content-media\")\n\t\t\t.where(\"scope_type\", \"=\", \"collection\")\n\t\t\t.where(\"scope_key\", \"=\", input.collectionSlug)\n\t\t\t.where(\"collection_id\", \"=\", input.collectionId)\n\t\t\t.where(\n\t\t\t\tsql<boolean>`EXISTS (\n\t\t\t\t\tSELECT 1\n\t\t\t\t\tFROM _emdash_media_usage_work AS work\n\t\t\t\t\tWHERE work.collection_id = ${input.collectionId}\n\t\t\t\t\t\tAND work.content_id = ${input.contentId}\n\t\t\t\t\t\tAND work.work_version = ${input.workVersion}\n\t\t\t\t\t\tAND work.state = 'failed'\n\t\t\t\t\t\tAND work.last_error_code = ${input.errorCode}\n\t\t\t\t)`,\n\t\t\t)\n\t\t\t.where(\n\t\t\t\tsql<boolean>`EXISTS (\n\t\t\t\t\tSELECT 1\n\t\t\t\t\tFROM _emdash_collections AS collection\n\t\t\t\t\tWHERE collection.id = ${input.collectionId}\n\t\t\t\t\t\tAND collection.slug = ${input.collectionSlug}\n\t\t\t\t)`,\n\t\t\t)\n\t\t\t.executeTakeFirst();\n\t\treturn Number(result.numUpdatedRows ?? 0) > 0;\n\t}\n\n\tasync findIndexStatus(\n\t\tidentity: MediaUsageIndexStatusIdentity,\n\t): Promise<MediaUsageIndexStatus | null> {\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"_emdash_media_usage_index_status\")\n\t\t\t.selectAll()\n\t\t\t.where(\"adapter_id\", \"=\", identity.adapterId)\n\t\t\t.where(\"scope_type\", \"=\", identity.scopeType)\n\t\t\t.where(\"scope_key\", \"=\", identity.scopeKey)\n\t\t\t.executeTakeFirst();\n\n\t\treturn row ? rowToIndexStatus(row) : null;\n\t}\n\n\tprivate async findIndexStatusForCollection(\n\t\tidentity: MediaUsageIndexStatusIdentity,\n\t\tcollectionId: string,\n\t): Promise<MediaUsageIndexStatus | null> {\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"_emdash_media_usage_index_status\")\n\t\t\t.selectAll()\n\t\t\t.where(\"adapter_id\", \"=\", identity.adapterId)\n\t\t\t.where(\"scope_type\", \"=\", identity.scopeType)\n\t\t\t.where(\"scope_key\", \"=\", identity.scopeKey)\n\t\t\t.where(\"collection_id\", \"=\", collectionId)\n\t\t\t.executeTakeFirst();\n\t\treturn row ? rowToIndexStatus(row) : null;\n\t}\n\n\tasync deleteIndexStatus(\n\t\tidentity: MediaUsageIndexStatusIdentity,\n\t\tcollectionId?: string,\n\t): Promise<number> {\n\t\tlet query = this.db\n\t\t\t.deleteFrom(\"_emdash_media_usage_index_status\")\n\t\t\t.where(\"adapter_id\", \"=\", identity.adapterId)\n\t\t\t.where(\"scope_type\", \"=\", identity.scopeType)\n\t\t\t.where(\"scope_key\", \"=\", identity.scopeKey);\n\t\tif (collectionId !== undefined) query = query.where(\"collection_id\", \"=\", collectionId);\n\t\tconst result = await query.executeTakeFirst();\n\t\treturn Number(result.numDeletedRows ?? 0);\n\t}\n\n\tprivate sortableUtcTimestamp(): RawBuilder<string> {\n\t\treturn isPostgres(this.db)\n\t\t\t? sql<string>`to_char(clock_timestamp() AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')`\n\t\t\t: sql<string>`strftime('%Y-%m-%dT%H:%M:%fZ', 'now')`;\n\t}\n\n\tprivate async findCurrentUsagePage(\n\t\tapplyFilter: (\n\t\t\tquery: ReturnType<MediaUsageRepository[\"currentUsageBaseQuery\"]>,\n\t\t) => ReturnType<MediaUsageRepository[\"currentUsageBaseQuery\"]>,\n\t\toptions: FindMediaUsageOptions,\n\t): Promise<FindManyResult<MediaUsageRecord>> {\n\t\tconst limit = Math.min(Math.max(1, options.limit ?? 50), 100);\n\t\tlet query = applyFilter(this.currentUsageBaseQuery())\n\t\t\t.orderBy(\"u.id\", \"asc\")\n\t\t\t.limit(limit + 1);\n\n\t\tif (options.cursor) {\n\t\t\tconst { id } = decodeCursor(options.cursor);\n\t\t\tquery = query.where(\"u.id\", \">\", id);\n\t\t}\n\n\t\tconst rows = await query.execute();\n\t\tconst items = rows.slice(0, limit).map(rowToUsageRecord);\n\t\tconst result: FindManyResult<MediaUsageRecord> = { items };\n\n\t\tif (rows.length > limit && items.length > 0) {\n\t\t\tconst last = items.at(-1)!;\n\t\t\tresult.nextCursor = encodeCursor(last.occurrence.id, last.occurrence.id);\n\t\t}\n\n\t\treturn result;\n\t}\n\n\tprivate currentUsageBaseQuery() {\n\t\treturn this.db\n\t\t\t.selectFrom(\"_emdash_media_usage_sources as s\")\n\t\t\t.innerJoin(\"_emdash_media_usage as u\", (join) =>\n\t\t\t\tjoin\n\t\t\t\t\t.onRef(\"u.source_key\", \"=\", \"s.source_key\")\n\t\t\t\t\t.onRef(\"u.generation\", \"=\", \"s.current_generation\"),\n\t\t\t)\n\t\t\t.select(currentUsageSelect);\n\t}\n\n\tprivate currentContentMediaUsageBaseQuery() {\n\t\treturn this.db\n\t\t\t.selectFrom(\"_emdash_media_usage as u\")\n\t\t\t.crossJoin(\"_emdash_media_usage_sources as s\")\n\t\t\t.innerJoin(\"_emdash_collections as collection\", \"collection.slug\", \"s.collection_slug\")\n\t\t\t.whereRef(\"s.source_key\", \"=\", \"u.source_key\")\n\t\t\t.whereRef(\"s.current_generation\", \"=\", \"u.generation\")\n\t\t\t.where(\"s.source_type\", \"=\", \"content\")\n\t\t\t.where(\"s.collection_slug\", \"is not\", null)\n\t\t\t.where(\"s.content_id\", \"is not\", null)\n\t\t\t.where(\"s.source_variant\", \"in\", [\"columns\", \"draft_overlay\"])\n\t\t\t.where(contentSourceMatchesActiveCollection(\"s\", \"collection.id\"))\n\t\t\t.where(CONTENT_SOURCE_ELIGIBILITY);\n\t}\n\n\tprivate async deleteOrphanCandidateIds(\n\t\tids: readonly string[],\n\t\tcutoff: string,\n\t\tcleanupLease?: MediaUsageCleanupLease,\n\t\tcanIssueStatement?: () => boolean,\n\t): Promise<number> {\n\t\tlet deleted = 0;\n\t\tfor (const idBatch of chunks([...ids], cleanupDeleteBatchSize(cleanupLease))) {\n\t\t\tif (!canIssueCleanupStatement(canIssueStatement)) break;\n\t\t\tif (cleanupLease) {\n\t\t\t\tawait this.markOrphanCandidatesForCleanup(idBatch, cutoff, cleanupLease);\n\t\t\t\tif (!canIssueCleanupStatement(canIssueStatement)) break;\n\t\t\t}\n\t\t\tlet query = this.db\n\t\t\t\t.deleteFrom(\"_emdash_media_usage\")\n\t\t\t\t.where(\"id\", \"in\", idBatch)\n\t\t\t\t.where(\"created_at\", \"<\", cutoff)\n\t\t\t\t.where(\n\t\t\t\t\tsql<boolean>`NOT EXISTS (SELECT 1 FROM _emdash_media_usage_sources source WHERE source.source_key = _emdash_media_usage.source_key)`,\n\t\t\t\t)\n\t\t\t\t.where(this.noActiveGenerationWriteExpression());\n\t\t\tif (cleanupLease) {\n\t\t\t\tquery = query\n\t\t\t\t\t.where(\"cleanup_lease_token\", \"=\", cleanupLease.leaseToken)\n\t\t\t\t\t.where(this.activeCleanupLeaseExpression(cleanupLease));\n\t\t\t}\n\t\t\tconst result = await query.executeTakeFirst();\n\t\t\tdeleted += Number(result.numDeletedRows ?? 0);\n\t\t}\n\t\treturn deleted;\n\t}\n\n\tprivate async deleteStaleCandidateIds(\n\t\tids: readonly string[],\n\t\tcutoff: string,\n\t\tcleanupLease?: MediaUsageCleanupLease,\n\t\tcanIssueStatement?: () => boolean,\n\t): Promise<number> {\n\t\tlet deleted = 0;\n\t\tfor (const idBatch of chunks([...ids], cleanupDeleteBatchSize(cleanupLease))) {\n\t\t\tif (!canIssueCleanupStatement(canIssueStatement)) break;\n\t\t\tif (cleanupLease) {\n\t\t\t\tawait this.markStaleCandidatesForCleanup(idBatch, cutoff, cleanupLease);\n\t\t\t\tif (!canIssueCleanupStatement(canIssueStatement)) break;\n\t\t\t}\n\t\t\tlet query = this.db\n\t\t\t\t.deleteFrom(\"_emdash_media_usage\")\n\t\t\t\t.where(\"id\", \"in\", idBatch)\n\t\t\t\t.where(\"created_at\", \"<\", cutoff)\n\t\t\t\t.where((eb) =>\n\t\t\t\t\teb.exists(\n\t\t\t\t\t\teb\n\t\t\t\t\t\t\t.selectFrom(\"_emdash_media_usage_sources as source\")\n\t\t\t\t\t\t\t.select(\"source.source_key\")\n\t\t\t\t\t\t\t.whereRef(\"source.source_key\", \"=\", \"_emdash_media_usage.source_key\")\n\t\t\t\t\t\t\t.whereRef(\"source.current_generation\", \"!=\", \"_emdash_media_usage.generation\")\n\t\t\t\t\t\t\t.whereRef(\"_emdash_media_usage.created_at\", \"<\", \"source.indexed_at\"),\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t\t.where(this.noActiveGenerationWriteExpression());\n\t\t\tif (cleanupLease) {\n\t\t\t\tquery = query\n\t\t\t\t\t.where(\"cleanup_lease_token\", \"=\", cleanupLease.leaseToken)\n\t\t\t\t\t.where(this.activeCleanupLeaseExpression(cleanupLease));\n\t\t\t}\n\t\t\tconst result = await query.executeTakeFirst();\n\t\t\tdeleted += Number(result.numDeletedRows ?? 0);\n\t\t}\n\t\treturn deleted;\n\t}\n\n\tprivate async deleteAbandonedCandidateIds(\n\t\tids: readonly string[],\n\t\tcutoff: string,\n\t\tcleanupLease?: MediaUsageCleanupLease,\n\t\tcanIssueStatement?: () => boolean,\n\t): Promise<number> {\n\t\tlet deleted = 0;\n\t\tfor (const idBatch of chunks([...ids], cleanupDeleteBatchSize(cleanupLease))) {\n\t\t\tif (!canIssueCleanupStatement(canIssueStatement)) break;\n\t\t\tif (cleanupLease) {\n\t\t\t\tawait this.markAbandonedCandidatesForCleanup(idBatch, cutoff, cleanupLease);\n\t\t\t\tif (!canIssueCleanupStatement(canIssueStatement)) break;\n\t\t\t}\n\t\t\tlet query = this.db\n\t\t\t\t.deleteFrom(\"_emdash_media_usage\")\n\t\t\t\t.where(\"id\", \"in\", idBatch)\n\t\t\t\t.where(\"created_at\", \"<\", cutoff)\n\t\t\t\t.where((eb) =>\n\t\t\t\t\teb.exists(\n\t\t\t\t\t\teb\n\t\t\t\t\t\t\t.selectFrom(\"_emdash_media_usage_sources as source\")\n\t\t\t\t\t\t\t.select(\"source.source_key\")\n\t\t\t\t\t\t\t.whereRef(\"source.source_key\", \"=\", \"_emdash_media_usage.source_key\")\n\t\t\t\t\t\t\t.whereRef(\"source.current_generation\", \"!=\", \"_emdash_media_usage.generation\")\n\t\t\t\t\t\t\t.whereRef(\"_emdash_media_usage.created_at\", \">=\", \"source.indexed_at\"),\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t\t.where(this.noActiveGenerationWriteExpression());\n\t\t\tif (cleanupLease) {\n\t\t\t\tquery = query\n\t\t\t\t\t.where(\"cleanup_lease_token\", \"=\", cleanupLease.leaseToken)\n\t\t\t\t\t.where(this.activeCleanupLeaseExpression(cleanupLease));\n\t\t\t}\n\t\t\tconst result = await query.executeTakeFirst();\n\t\t\tdeleted += Number(result.numDeletedRows ?? 0);\n\t\t}\n\t\treturn deleted;\n\t}\n\n\tprivate async markOrphanCandidatesForCleanup(\n\t\tids: readonly string[],\n\t\tcutoff: string,\n\t\tcleanupLease: MediaUsageCleanupLease,\n\t): Promise<void> {\n\t\tawait this.db\n\t\t\t.updateTable(\"_emdash_media_usage\")\n\t\t\t.set({ cleanup_lease_token: cleanupLease.leaseToken })\n\t\t\t.where(\"id\", \"in\", ids)\n\t\t\t.where(\"created_at\", \"<\", cutoff)\n\t\t\t.where(\n\t\t\t\tsql<boolean>`NOT EXISTS (SELECT 1 FROM _emdash_media_usage_sources source WHERE source.source_key = _emdash_media_usage.source_key)`,\n\t\t\t)\n\t\t\t.where(this.noActiveGenerationWriteExpression())\n\t\t\t.where(this.activeCleanupLeaseExpression(cleanupLease))\n\t\t\t.execute();\n\t}\n\n\tprivate async markStaleCandidatesForCleanup(\n\t\tids: readonly string[],\n\t\tcutoff: string,\n\t\tcleanupLease: MediaUsageCleanupLease,\n\t): Promise<void> {\n\t\tawait this.db\n\t\t\t.updateTable(\"_emdash_media_usage\")\n\t\t\t.set({ cleanup_lease_token: cleanupLease.leaseToken })\n\t\t\t.where(\"id\", \"in\", ids)\n\t\t\t.where(\"created_at\", \"<\", cutoff)\n\t\t\t.where((eb) =>\n\t\t\t\teb.exists(\n\t\t\t\t\teb\n\t\t\t\t\t\t.selectFrom(\"_emdash_media_usage_sources as source\")\n\t\t\t\t\t\t.select(\"source.source_key\")\n\t\t\t\t\t\t.whereRef(\"source.source_key\", \"=\", \"_emdash_media_usage.source_key\")\n\t\t\t\t\t\t.whereRef(\"source.current_generation\", \"!=\", \"_emdash_media_usage.generation\")\n\t\t\t\t\t\t.whereRef(\"_emdash_media_usage.created_at\", \"<\", \"source.indexed_at\"),\n\t\t\t\t),\n\t\t\t)\n\t\t\t.where(this.noActiveGenerationWriteExpression())\n\t\t\t.where(this.activeCleanupLeaseExpression(cleanupLease))\n\t\t\t.execute();\n\t}\n\n\tprivate async markAbandonedCandidatesForCleanup(\n\t\tids: readonly string[],\n\t\tcutoff: string,\n\t\tcleanupLease: MediaUsageCleanupLease,\n\t): Promise<void> {\n\t\tawait this.db\n\t\t\t.updateTable(\"_emdash_media_usage\")\n\t\t\t.set({ cleanup_lease_token: cleanupLease.leaseToken })\n\t\t\t.where(\"id\", \"in\", ids)\n\t\t\t.where(\"created_at\", \"<\", cutoff)\n\t\t\t.where((eb) =>\n\t\t\t\teb.exists(\n\t\t\t\t\teb\n\t\t\t\t\t\t.selectFrom(\"_emdash_media_usage_sources as source\")\n\t\t\t\t\t\t.select(\"source.source_key\")\n\t\t\t\t\t\t.whereRef(\"source.source_key\", \"=\", \"_emdash_media_usage.source_key\")\n\t\t\t\t\t\t.whereRef(\"source.current_generation\", \"!=\", \"_emdash_media_usage.generation\")\n\t\t\t\t\t\t.whereRef(\"_emdash_media_usage.created_at\", \">=\", \"source.indexed_at\"),\n\t\t\t\t),\n\t\t\t)\n\t\t\t.where(this.noActiveGenerationWriteExpression())\n\t\t\t.where(this.activeCleanupLeaseExpression(cleanupLease))\n\t\t\t.execute();\n\t}\n\n\tprivate noActiveGenerationWriteExpression(usageTable = \"_emdash_media_usage\") {\n\t\tconst sourceKey = sql.ref(`${usageTable}.source_key`);\n\t\tconst generation = sql.ref(`${usageTable}.generation`);\n\t\treturn sql<boolean>`NOT EXISTS (\n\t\t\t\tSELECT 1\n\t\t\t\tFROM _emdash_media_usage_generation_writes AS writer\n\t\t\t\tWHERE writer.source_key = ${sourceKey}\n\t\t\t\t\tAND writer.generation = ${generation}\n\t\t\t\t\tAND ${this.generationWriteLeaseExpiryIsInFuture(\"writer.expires_at\")}\n\t\t\t)`;\n\t}\n\n\tprivate activeCleanupLeaseExpression(cleanupLease: MediaUsageCleanupLease) {\n\t\tconst rowLock = isPostgres(this.db) ? sql` FOR UPDATE` : sql``;\n\t\treturn sql<boolean>`EXISTS (\n\t\t\t\tSELECT 1\n\t\t\t\tFROM _emdash_media_usage_cleanup AS cleanup\n\t\t\t\tWHERE cleanup.task_key = 'projection_gc'\n\t\t\t\t\tAND cleanup.lease_token = ${cleanupLease.leaseToken}\n\t\t\t\t\tAND ${this.cleanupLeaseExpiryIsInFuture(\"cleanup.lease_expires_at\")}\n\t\t\t\t${rowLock}\n\t\t\t)`;\n\t}\n\n\tprivate cleanupLeaseExpiryIsInFuture(column: string) {\n\t\tconst leaseExpiresAt = sql.ref(column);\n\t\treturn isPostgres(this.db)\n\t\t\t? sql<boolean>`${leaseExpiresAt}::timestamptz > clock_timestamp()`\n\t\t\t: sql<boolean>`${leaseExpiresAt} > strftime('%Y-%m-%dT%H:%M:%fZ', 'now')`;\n\t}\n\n\tprivate cleanupTimestampIsDue(column: string) {\n\t\tconst timestamp = sql.ref(column);\n\t\treturn isPostgres(this.db)\n\t\t\t? sql<boolean>`${timestamp}::timestamptz <= clock_timestamp()`\n\t\t\t: sql<boolean>`${timestamp} <= strftime('%Y-%m-%dT%H:%M:%fZ', 'now')`;\n\t}\n\n\tprivate cleanupTimestampOffset(offsetSeconds: number): RawBuilder<string> {\n\t\tif (isPostgres(this.db)) {\n\t\t\treturn sql<string>`to_char(\n\t\t\t\t(clock_timestamp() AT TIME ZONE 'UTC') + (${offsetSeconds} * INTERVAL '1 second'),\n\t\t\t\t'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"'\n\t\t\t)`;\n\t\t}\n\t\treturn sql<string>`strftime(\n\t\t\t'%Y-%m-%dT%H:%M:%fZ',\n\t\t\t'now',\n\t\t\t${`${offsetSeconds >= 0 ? \"+\" : \"\"}${offsetSeconds} seconds`}\n\t\t)`;\n\t}\n\n\tprivate generationWriteLeaseHasExpired(column: string) {\n\t\tconst leaseExpiresAt = sql.ref(column);\n\t\treturn isPostgres(this.db)\n\t\t\t? sql<boolean>`${leaseExpiresAt}::timestamptz <= clock_timestamp()`\n\t\t\t: sql<boolean>`${leaseExpiresAt} <= strftime('%Y-%m-%dT%H:%M:%fZ', 'now')`;\n\t}\n\n\tprivate async deleteSourceKeys(sourceKeys: readonly string[]): Promise<number> {\n\t\tconst uniqueSourceKeys = [...new Set(sourceKeys)];\n\t\tif (uniqueSourceKeys.length === 0) return 0;\n\n\t\treturn withTransaction(this.db, async (trx) => {\n\t\t\tawait this.lockCleanupBeforeSourceDelete(trx);\n\t\t\tlet deleted = 0;\n\t\t\tfor (const sourceKeyBatch of chunks(uniqueSourceKeys, SQL_BATCH_SIZE)) {\n\t\t\t\tconst result = await trx\n\t\t\t\t\t.deleteFrom(\"_emdash_media_usage_sources\")\n\t\t\t\t\t.where(\"source_key\", \"in\", sourceKeyBatch)\n\t\t\t\t\t.executeTakeFirst();\n\t\t\t\tdeleted += Number(result.numDeletedRows ?? 0);\n\n\t\t\t\tawait trx\n\t\t\t\t\t.updateTable(\"_emdash_media_usage\")\n\t\t\t\t\t.set({ cleanup_lease_token: null })\n\t\t\t\t\t.where(\"source_key\", \"in\", sourceKeyBatch)\n\t\t\t\t\t.execute();\n\t\t\t\tawait trx\n\t\t\t\t\t.deleteFrom(\"_emdash_media_usage\")\n\t\t\t\t\t.where(\"source_key\", \"in\", sourceKeyBatch)\n\t\t\t\t\t.execute();\n\t\t\t}\n\t\t\treturn deleted;\n\t\t});\n\t}\n\n\tprivate async deleteSourceGenerationOccurrences(\n\t\tdb: DatabaseExecutor,\n\t\tsourceKey: string,\n\t\tgeneration: string,\n\t): Promise<void> {\n\t\tawait db\n\t\t\t.updateTable(\"_emdash_media_usage\")\n\t\t\t.set({ cleanup_lease_token: null })\n\t\t\t.where(\"source_key\", \"=\", sourceKey)\n\t\t\t.where(\"generation\", \"=\", generation)\n\t\t\t.execute();\n\t\tawait db\n\t\t\t.deleteFrom(\"_emdash_media_usage\")\n\t\t\t.where(\"source_key\", \"=\", sourceKey)\n\t\t\t.where(\"generation\", \"=\", generation)\n\t\t\t.execute();\n\t}\n\n\tprivate async lockCleanupBeforeSourceDelete(db: DatabaseExecutor): Promise<void> {\n\t\tif (!isPostgres(this.db)) return;\n\t\tawait sql`\n\t\t\tSELECT 1\n\t\t\tFROM _emdash_media_usage_cleanup\n\t\t\tWHERE task_key = 'projection_gc'\n\t\t\tFOR SHARE\n\t\t`.execute(db);\n\t}\n\n\tprivate async insertOccurrences(\n\t\tdb: DatabaseExecutor,\n\t\tsourceKey: string,\n\t\tgeneration: string,\n\t\toccurrences: readonly MediaUsageOccurrenceInput[],\n\t\tnow: string,\n\t): Promise<void> {\n\t\tif (occurrences.length === 0) return;\n\n\t\tconst rows = occurrences.map((occurrence) => ({\n\t\t\tid: ulid(),\n\t\t\tsource_key: sourceKey,\n\t\t\tgeneration,\n\t\t\tfield_slug: occurrence.fieldSlug,\n\t\t\tfield_path: occurrence.fieldPath,\n\t\t\toccurrence_index: occurrence.occurrenceIndex ?? 0,\n\t\t\treference_type: occurrence.referenceType,\n\t\t\tmedia_id: occurrence.mediaId,\n\t\t\tprovider: occurrence.provider,\n\t\t\tprovider_asset_id: occurrence.providerAssetId,\n\t\t\tmedia_kind: occurrence.mediaKind ?? null,\n\t\t\tmime_type: occurrence.mimeType ?? null,\n\t\t\tcreated_at: now,\n\t\t}));\n\n\t\tfor (const rowBatch of chunks(rows, OCCURRENCE_INSERT_BATCH_SIZE)) {\n\t\t\tawait db.insertInto(\"_emdash_media_usage\").values(rowBatch).execute();\n\t\t}\n\t}\n\n\tprivate async lockCanonicalSourceCollection(\n\t\tdb: DatabaseExecutor,\n\t\tsource: MediaUsageSourceInput,\n\t): Promise<boolean> {\n\t\tif (source.collectionId === undefined || source.collectionId === null) return true;\n\t\tif (!source.collectionSlug) return false;\n\t\tif (!isPostgres(this.db)) return true;\n\t\tconst collection = await db\n\t\t\t.selectFrom(\"_emdash_collections\")\n\t\t\t.select(\"id\")\n\t\t\t.where(\"id\", \"=\", source.collectionId)\n\t\t\t.where(\"slug\", \"=\", source.collectionSlug)\n\t\t\t.forKeyShare()\n\t\t\t.executeTakeFirst();\n\t\treturn collection !== undefined;\n\t}\n\n\tprivate async upsertSource(\n\t\tdb: DatabaseExecutor,\n\t\tsource: MediaUsageSourceInput,\n\t\tgeneration: string,\n\t\tnow: string,\n\t\tleaseToken: string,\n\t): Promise<boolean> {\n\t\tconst row = this.buildSourceRow(source, generation, now);\n\t\treturn this.persistSourceIfWriteLease(\n\t\t\tdb,\n\t\t\trow,\n\t\t\tleaseToken,\n\t\t\tsql`\n\t\t\t\tON CONFLICT (source_key) DO UPDATE SET\n\t\t\t\t\tsource_type = excluded.source_type,\n\t\t\t\t\tcollection_id = excluded.collection_id,\n\t\t\t\t\tcollection_slug = excluded.collection_slug,\n\t\t\t\t\tcontent_id = excluded.content_id,\n\t\t\t\t\tsource_variant = excluded.source_variant,\n\t\t\t\t\tlocale = excluded.locale,\n\t\t\t\t\ttranslation_group = excluded.translation_group,\n\t\t\t\t\tcontent_slug = excluded.content_slug,\n\t\t\t\t\tcontent_title = excluded.content_title,\n\t\t\t\t\tcontent_status = excluded.content_status,\n\t\t\t\t\tcontent_scheduled_at = excluded.content_scheduled_at,\n\t\t\t\t\tcontent_deleted_at = excluded.content_deleted_at,\n\t\t\t\t\trevision_id = excluded.revision_id,\n\t\t\t\t\tcurrent_generation = excluded.current_generation,\n\t\t\t\t\tschema_version = excluded.schema_version,\n\t\t\t\t\tsource_updated_at = excluded.source_updated_at,\n\t\t\t\t\tsource_version = excluded.source_version,\n\t\t\t\t\tsource_fingerprint = excluded.source_fingerprint,\n\t\t\t\t\tidentity_version = excluded.identity_version,\n\t\t\t\t\tsource_completeness = excluded.source_completeness,\n\t\t\t\t\tlast_attempted_at = excluded.last_attempted_at,\n\t\t\t\t\tlast_error_code = excluded.last_error_code,\n\t\t\t\t\tindexed_at = excluded.indexed_at,\n\t\t\t\t\tupdated_at = excluded.updated_at\n\t\t\t`,\n\t\t);\n\t}\n\n\tprivate async insertSourceIfAbsent(\n\t\tdb: DatabaseExecutor,\n\t\trow: ReturnType<MediaUsageRepository[\"buildSourceRow\"]>,\n\t\tleaseToken: string,\n\t): Promise<boolean> {\n\t\treturn this.persistSourceIfWriteLease(\n\t\t\tdb,\n\t\t\trow,\n\t\t\tleaseToken,\n\t\t\tsql`ON CONFLICT (source_key) DO NOTHING`,\n\t\t);\n\t}\n\n\tprivate async persistSourceIfWriteLease(\n\t\tdb: DatabaseExecutor,\n\t\trow:\n\t\t\t| ReturnType<MediaUsageRepository[\"buildSourceRow\"]>\n\t\t\t| ReturnType<MediaUsageRepository[\"buildAttemptedSourceRow\"]>,\n\t\tleaseToken: string,\n\t\tconflict: RawBuilder<unknown>,\n\t): Promise<boolean> {\n\t\tconst result = await sql`\n\t\t\tINSERT INTO _emdash_media_usage_sources (\n\t\t\t\tsource_key,\n\t\t\t\tsource_type,\n\t\t\t\tcollection_id,\n\t\t\t\tcollection_slug,\n\t\t\t\tcontent_id,\n\t\t\t\tsource_variant,\n\t\t\t\tlocale,\n\t\t\t\ttranslation_group,\n\t\t\t\tcontent_slug,\n\t\t\t\tcontent_title,\n\t\t\t\tcontent_status,\n\t\t\t\tcontent_scheduled_at,\n\t\t\t\tcontent_deleted_at,\n\t\t\t\trevision_id,\n\t\t\t\tcurrent_generation,\n\t\t\t\tschema_version,\n\t\t\t\tsource_updated_at,\n\t\t\t\tsource_version,\n\t\t\t\tsource_fingerprint,\n\t\t\t\tidentity_version,\n\t\t\t\tsource_completeness,\n\t\t\t\tlast_attempted_at,\n\t\t\t\tlast_error_code,\n\t\t\t\tindexed_at,\n\t\t\t\tupdated_at\n\t\t\t)\n\t\t\tSELECT\n\t\t\t\t${row.source_key},\n\t\t\t\t${row.source_type},\n\t\t\t\t${row.collection_id},\n\t\t\t\t${row.collection_slug},\n\t\t\t\t${row.content_id},\n\t\t\t\t${row.source_variant},\n\t\t\t\t${row.locale},\n\t\t\t\t${row.translation_group},\n\t\t\t\t${row.content_slug},\n\t\t\t\t${row.content_title},\n\t\t\t\t${row.content_status},\n\t\t\t\t${row.content_scheduled_at},\n\t\t\t\t${row.content_deleted_at},\n\t\t\t\t${row.revision_id},\n\t\t\t\t${row.current_generation},\n\t\t\t\t${row.schema_version},\n\t\t\t\t${row.source_updated_at},\n\t\t\t\t${row.source_version},\n\t\t\t\t${row.source_fingerprint},\n\t\t\t\t${row.identity_version},\n\t\t\t\t${row.source_completeness},\n\t\t\t\t${row.last_attempted_at},\n\t\t\t\t${row.last_error_code},\n\t\t\t\t${row.indexed_at},\n\t\t\t\t${row.updated_at}\n\t\t\tWHERE EXISTS (\n\t\t\t\tSELECT 1\n\t\t\t\tFROM _emdash_media_usage_generation_writes\n\t\t\t\tWHERE source_key = ${row.source_key}\n\t\t\t\t\tAND generation = ${row.current_generation}\n\t\t\t\t\tAND lease_token = ${leaseToken}\n\t\t\t\t\tAND ${this.generationWriteLeaseExpiryIsInFuture(\"expires_at\")}\n\t\t\t)\n\t\t\tAND ${this.currentCollectionExists(row.collection_id, row.collection_slug)}\n\t\t\tAND ${this.currentCanonicalContentExists(row)}\n\t\t\t${conflict}\n\t\t`.execute(db);\n\t\treturn Number(result.numAffectedRows ?? 0) > 0;\n\t}\n\n\tprivate generationWriteLeaseExpression(\n\t\trow: ReturnType<MediaUsageRepository[\"buildSourceRow\"]>,\n\t\tleaseToken: string,\n\t) {\n\t\treturn (eb: ExpressionBuilder<Database, \"_emdash_media_usage_sources\">) =>\n\t\t\teb.exists(\n\t\t\t\teb\n\t\t\t\t\t.selectFrom(\"_emdash_media_usage_generation_writes\")\n\t\t\t\t\t.select(\"source_key\")\n\t\t\t\t\t.where(\"source_key\", \"=\", row.source_key)\n\t\t\t\t\t.where(\"generation\", \"=\", row.current_generation)\n\t\t\t\t\t.where(\"lease_token\", \"=\", leaseToken)\n\t\t\t\t\t.where(\n\t\t\t\t\t\tthis.generationWriteLeaseExpiryIsInFuture(\n\t\t\t\t\t\t\t\"_emdash_media_usage_generation_writes.expires_at\",\n\t\t\t\t\t\t),\n\t\t\t\t\t),\n\t\t\t);\n\t}\n\n\tprivate generationWriteLeaseExpiryIsInFuture(column: string) {\n\t\tconst leaseExpiresAt = sql.ref(column);\n\t\treturn isPostgres(this.db)\n\t\t\t? sql<boolean>`${leaseExpiresAt}::timestamptz > clock_timestamp()`\n\t\t\t: sql<boolean>`${leaseExpiresAt} > strftime('%Y-%m-%dT%H:%M:%fZ', 'now')`;\n\t}\n\n\tprivate async withGenerationWriteLease(\n\t\tsource: Pick<MediaUsageSourceInput, \"sourceKey\" | \"collectionId\" | \"collectionSlug\">,\n\t\tgeneration: string,\n\t\twrite: (leaseToken: string, startedAt: string) => Promise<void>,\n\t): Promise<boolean> {\n\t\tconst leaseToken = ulid();\n\t\tconst lease = await sql<{ created_at: string }>`\n\t\t\tINSERT INTO _emdash_media_usage_generation_writes (\n\t\t\t\tsource_key, generation, lease_token, expires_at, created_at\n\t\t\t)\n\t\t\tSELECT\n\t\t\t\t${source.sourceKey},\n\t\t\t\t${generation},\n\t\t\t\t${leaseToken},\n\t\t\t\t${this.generationWriteLeaseTimestampOffset(MEDIA_USAGE_GENERATION_WRITE_LEASE_MS / 1000)},\n\t\t\t\t${this.generationWriteLeaseTimestampOffset(0)}\n\t\t\tWHERE ${this.currentCollectionExists(\n\t\t\t\tsource.collectionId ?? null,\n\t\t\t\tsource.collectionSlug ?? null,\n\t\t\t)}\n\t\t\tRETURNING created_at\n\t\t`.execute(this.db);\n\t\tconst owner = lease.rows[0];\n\t\tif (!owner) return false;\n\n\t\ttry {\n\t\t\tawait write(leaseToken, owner.created_at);\n\t\t\treturn true;\n\t\t} finally {\n\t\t\ttry {\n\t\t\t\tawait this.db\n\t\t\t\t\t.deleteFrom(\"_emdash_media_usage_generation_writes\")\n\t\t\t\t\t.where(\"source_key\", \"=\", source.sourceKey)\n\t\t\t\t\t.where(\"generation\", \"=\", generation)\n\t\t\t\t\t.where(\"lease_token\", \"=\", leaseToken)\n\t\t\t\t\t.execute();\n\t\t\t} catch (error) {\n\t\t\t\tconsole.error(\"[media-usage] Failed to release generation write lease:\", error);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate generationWriteLeaseTimestampOffset(offsetSeconds: number): RawBuilder<string> {\n\t\tif (isPostgres(this.db)) {\n\t\t\treturn sql<string>`to_char(\n\t\t\t\t(clock_timestamp() AT TIME ZONE 'UTC') + (${offsetSeconds} * INTERVAL '1 second'),\n\t\t\t\t'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"'\n\t\t\t)`;\n\t\t}\n\t\treturn sql<string>`strftime(\n\t\t\t'%Y-%m-%dT%H:%M:%fZ',\n\t\t\t'now',\n\t\t\t${`${offsetSeconds >= 0 ? \"+\" : \"\"}${offsetSeconds} seconds`}\n\t\t)`;\n\t}\n\n\tprivate async updateSourceIfGeneration(\n\t\tdb: DatabaseExecutor,\n\t\trow: ReturnType<MediaUsageRepository[\"buildSourceRow\"]>,\n\t\texpectedCurrentGeneration: string,\n\t\tleaseToken: string,\n\t): Promise<boolean> {\n\t\tconst result = await db\n\t\t\t.updateTable(\"_emdash_media_usage_sources\")\n\t\t\t.set(this.sourceUpdateSet(row))\n\t\t\t.where(\"source_key\", \"=\", row.source_key)\n\t\t\t.where(\"current_generation\", \"=\", expectedCurrentGeneration)\n\t\t\t.where(this.generationWriteLeaseExpression(row, leaseToken))\n\t\t\t.where(this.currentCollectionExists(row.collection_id, row.collection_slug))\n\t\t\t.where(this.currentCanonicalContentExists(row))\n\t\t\t.executeTakeFirst();\n\t\treturn Number(result.numUpdatedRows ?? 0) > 0;\n\t}\n\n\tprivate async updateSourceIfMatching(\n\t\tdb: DatabaseExecutor,\n\t\trow: ReturnType<MediaUsageRepository[\"buildSourceRow\"]>,\n\t\texpectedSource: MediaUsageSource,\n\t\tleaseToken: string,\n\t): Promise<boolean> {\n\t\tconst result = await db\n\t\t\t.updateTable(\"_emdash_media_usage_sources\")\n\t\t\t.set(this.sourceUpdateSet(row))\n\t\t\t.where(\"source_key\", \"=\", row.source_key)\n\t\t\t.where(this.sourceMatchExpression(expectedSource))\n\t\t\t.where(this.generationWriteLeaseExpression(row, leaseToken))\n\t\t\t.where(this.currentCollectionExists(row.collection_id, row.collection_slug))\n\t\t\t.where(this.currentCanonicalContentExists(row))\n\t\t\t.executeTakeFirst();\n\t\treturn Number(result.numUpdatedRows ?? 0) > 0;\n\t}\n\n\tprivate async updateAttemptedSourceIfMatching(\n\t\tdb: DatabaseExecutor,\n\t\tsource: MediaUsageSourceInput,\n\t\trow: ReturnType<MediaUsageRepository[\"buildAttemptedSourceRow\"]>,\n\t\texpectedSource: MediaUsageSource,\n\t): Promise<boolean> {\n\t\tconst result = await db\n\t\t\t.updateTable(\"_emdash_media_usage_sources\")\n\t\t\t.set(this.attemptedSourceUpdateSet(source, row))\n\t\t\t.where(\"source_key\", \"=\", row.source_key)\n\t\t\t.where(this.sourceMatchExpression(expectedSource))\n\t\t\t.where(this.currentCollectionExists(row.collection_id, row.collection_slug))\n\t\t\t.where(this.currentCanonicalContentExists(row))\n\t\t\t.executeTakeFirst();\n\t\treturn Number(result.numUpdatedRows ?? 0) > 0;\n\t}\n\n\tprivate sourceMatchExpression(expectedSource: MediaUsageSource) {\n\t\treturn (eb: ExpressionBuilder<Database, \"_emdash_media_usage_sources\">) =>\n\t\t\teb.and([\n\t\t\t\teb(\"current_generation\", \"=\", expectedSource.currentGeneration),\n\t\t\t\teb(\"source_completeness\", \"=\", expectedSource.sourceCompleteness),\n\t\t\t\tthis.nullableStringExpression(eb, \"collection_id\", expectedSource.collectionId),\n\t\t\t\tthis.nullableStringExpression(eb, \"updated_at\", expectedSource.updatedAt),\n\t\t\t\tthis.nullableStringExpression(eb, \"source_fingerprint\", expectedSource.sourceFingerprint),\n\t\t\t\tthis.nullableStringExpression(eb, \"source_updated_at\", expectedSource.sourceUpdatedAt),\n\t\t\t\tthis.nullableNumberExpression(eb, \"source_version\", expectedSource.sourceVersion),\n\t\t\t\tthis.nullableNumberExpression(eb, \"identity_version\", expectedSource.identityVersion),\n\t\t\t\tthis.nullableStringExpression(eb, \"revision_id\", expectedSource.revisionId),\n\t\t\t\tthis.nullableStringExpression(eb, \"last_attempted_at\", expectedSource.lastAttemptedAt),\n\t\t\t\tthis.nullableStringExpression(eb, \"last_error_code\", expectedSource.lastErrorCode),\n\t\t\t]);\n\t}\n\n\tprivate async projectionMatchesCurrentGeneration(\n\t\tsource: MediaUsageSourceInput,\n\t\texpectedCurrentGeneration: string,\n\t): Promise<boolean> {\n\t\tconst fingerprint = source.sourceFingerprint;\n\t\tif (!isMediaUsageProjectionFingerprint(fingerprint)) return false;\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"_emdash_media_usage_sources\")\n\t\t\t.select(\"source_key\")\n\t\t\t.where(\"source_key\", \"=\", source.sourceKey)\n\t\t\t.where(\"current_generation\", \"=\", expectedCurrentGeneration)\n\t\t\t.where(\"source_fingerprint\", \"=\", fingerprint!)\n\t\t\t.where(\"source_completeness\", \"=\", source.sourceCompleteness ?? \"complete\")\n\t\t\t.where(\"last_error_code\", \"is\", null)\n\t\t\t.where(\n\t\t\t\tthis.currentCollectionExists(source.collectionId ?? null, source.collectionSlug ?? null),\n\t\t\t)\n\t\t\t.executeTakeFirst();\n\t\treturn row !== undefined;\n\t}\n\n\tasync projectionMatchesExpectedSource(\n\t\tsource: MediaUsageSourceInput,\n\t\texpectedSource: MediaUsageSource,\n\t): Promise<boolean> {\n\t\tconst fingerprint = source.sourceFingerprint;\n\t\tif (\n\t\t\t!isMediaUsageProjectionFingerprint(fingerprint) ||\n\t\t\texpectedSource.sourceFingerprint !== fingerprint ||\n\t\t\texpectedSource.sourceCompleteness !== (source.sourceCompleteness ?? \"complete\") ||\n\t\t\texpectedSource.lastErrorCode !== null\n\t\t) {\n\t\t\treturn false;\n\t\t}\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"_emdash_media_usage_sources\")\n\t\t\t.select(\"source_key\")\n\t\t\t.where(\"source_key\", \"=\", source.sourceKey)\n\t\t\t.where(this.sourceMatchExpression(expectedSource))\n\t\t\t.where(\n\t\t\t\tthis.currentCollectionExists(source.collectionId ?? null, source.collectionSlug ?? null),\n\t\t\t)\n\t\t\t.executeTakeFirst();\n\t\treturn row !== undefined;\n\t}\n\n\tprivate nullableStringExpression(\n\t\teb: ExpressionBuilder<Database, \"_emdash_media_usage_sources\">,\n\t\tcolumn: MediaUsageSourceNullableStringColumn,\n\t\tvalue: string | null,\n\t) {\n\t\treturn value === null ? eb(column, \"is\", null) : eb(column, \"=\", value);\n\t}\n\n\tprivate currentCollectionExists(\n\t\tcollectionId: string | null,\n\t\tcollectionSlug: string | null,\n\t): RawBuilder<boolean> {\n\t\tif (collectionId === null) return sql<boolean>`1 = 1`;\n\t\treturn sql<boolean>`EXISTS (\n\t\t\tSELECT 1\n\t\t\tFROM _emdash_collections\n\t\t\tWHERE id = ${collectionId}\n\t\t\t\tAND slug = ${collectionSlug}\n\t\t)`;\n\t}\n\n\tprivate currentCanonicalContentExists(\n\t\trow:\n\t\t\t| ReturnType<MediaUsageRepository[\"buildSourceRow\"]>\n\t\t\t| ReturnType<MediaUsageRepository[\"buildAttemptedSourceRow\"]>,\n\t): RawBuilder<boolean> {\n\t\tif (row.collection_id === null || row.identity_version !== 1 || row.source_type !== \"content\") {\n\t\t\treturn sql<boolean>`1 = 1`;\n\t\t}\n\t\tif (\n\t\t\t!row.collection_slug ||\n\t\t\t!row.content_id ||\n\t\t\trow.source_version === null ||\n\t\t\trow.source_updated_at === null\n\t\t) {\n\t\t\treturn sql<boolean>`1 = 0`;\n\t\t}\n\t\tvalidateIdentifier(row.collection_slug, \"collection slug\");\n\t\tconst tableName = `ec_${row.collection_slug}`;\n\t\tvalidateIdentifier(tableName, \"content table\");\n\t\tconst revisionColumn =\n\t\t\trow.source_variant === \"columns\"\n\t\t\t\t? \"live_revision_id\"\n\t\t\t\t: row.source_variant === \"draft_overlay\"\n\t\t\t\t\t? \"draft_revision_id\"\n\t\t\t\t\t: null;\n\t\tif (!revisionColumn) return sql<boolean>`1 = 0`;\n\t\tconst revision = sql.ref(`content.${revisionColumn}`);\n\t\tconst revisionMatches =\n\t\t\trow.revision_id === null\n\t\t\t\t? sql<boolean>`${revision} IS NULL`\n\t\t\t\t: sql<boolean>`${revision} = ${row.revision_id}`;\n\t\treturn sql<boolean>`EXISTS (\n\t\t\tSELECT 1\n\t\t\tFROM ${sql.ref(tableName)} AS content\n\t\t\tWHERE content.id = ${row.content_id}\n\t\t\t\tAND content.version = ${row.source_version}\n\t\t\t\tAND content.updated_at = ${row.source_updated_at}\n\t\t\t\tAND ${revisionMatches}\n\t\t)`;\n\t}\n\n\tprivate nullableNumberExpression(\n\t\teb: ExpressionBuilder<Database, \"_emdash_media_usage_sources\">,\n\t\tcolumn: \"source_version\" | \"identity_version\",\n\t\tvalue: number | null,\n\t) {\n\t\treturn value === null ? eb(column, \"is\", null) : eb(column, \"=\", value);\n\t}\n\n\tprivate async contentRowExists(tableName: string, contentId: string): Promise<boolean> {\n\t\tconst result = await sql<{ id: string }>`\n\t\t\tSELECT id\n\t\t\tFROM ${sql.ref(tableName)}\n\t\t\tWHERE id = ${contentId}\n\t\t\tLIMIT 1\n\t\t`.execute(this.db);\n\t\treturn result.rows.length > 0;\n\t}\n\n\tprivate buildSourceRow(source: MediaUsageSourceInput, generation: string, now: string) {\n\t\treturn {\n\t\t\tsource_key: source.sourceKey,\n\t\t\tsource_type: source.sourceType,\n\t\t\tcollection_id: source.collectionId ?? null,\n\t\t\tcollection_slug: source.collectionSlug ?? null,\n\t\t\tcontent_id: source.contentId ?? null,\n\t\t\tsource_variant: source.sourceVariant,\n\t\t\tlocale: source.locale ?? null,\n\t\t\ttranslation_group: source.translationGroup ?? null,\n\t\t\tcontent_slug: source.contentSlug ?? null,\n\t\t\tcontent_title: source.contentTitle ?? null,\n\t\t\tcontent_status: source.contentStatus ?? null,\n\t\t\tcontent_scheduled_at: source.contentScheduledAt ?? null,\n\t\t\tcontent_deleted_at: source.contentDeletedAt ?? null,\n\t\t\trevision_id: source.revisionId ?? null,\n\t\t\tcurrent_generation: generation,\n\t\t\tschema_version: source.schemaVersion ?? 1,\n\t\t\tsource_updated_at: source.sourceUpdatedAt ?? null,\n\t\t\tsource_version: source.sourceVersion ?? null,\n\t\t\tsource_fingerprint: source.sourceFingerprint ?? null,\n\t\t\tidentity_version: source.identityVersion ?? null,\n\t\t\t// Complete means this source was fully refreshed for the extractor's current\n\t\t\t// schema/version coverage, not that every possible reference shape is known.\n\t\t\tsource_completeness: source.sourceCompleteness ?? \"complete\",\n\t\t\tlast_attempted_at: source.lastAttemptedAt ?? now,\n\t\t\tlast_error_code: null,\n\t\t\tindexed_at: now,\n\t\t\tupdated_at: now,\n\t\t};\n\t}\n\n\tprivate buildAttemptedSourceRow(source: MediaUsageSourceInput, generation: string, now: string) {\n\t\treturn {\n\t\t\tsource_key: source.sourceKey,\n\t\t\tsource_type: source.sourceType,\n\t\t\tcollection_id: source.collectionId ?? null,\n\t\t\tcollection_slug: source.collectionSlug ?? null,\n\t\t\tcontent_id: source.contentId ?? null,\n\t\t\tsource_variant: source.sourceVariant,\n\t\t\tlocale: source.locale ?? null,\n\t\t\ttranslation_group: source.translationGroup ?? null,\n\t\t\tcontent_slug: source.contentSlug ?? null,\n\t\t\tcontent_title: source.contentTitle ?? null,\n\t\t\tcontent_status: source.contentStatus ?? null,\n\t\t\tcontent_scheduled_at: source.contentScheduledAt ?? null,\n\t\t\tcontent_deleted_at: source.contentDeletedAt ?? null,\n\t\t\trevision_id: source.revisionId ?? null,\n\t\t\tcurrent_generation: generation,\n\t\t\tschema_version: source.schemaVersion ?? 1,\n\t\t\tsource_updated_at: source.sourceUpdatedAt ?? null,\n\t\t\tsource_version: source.sourceVersion ?? null,\n\t\t\tsource_fingerprint: source.sourceFingerprint ?? null,\n\t\t\tidentity_version: source.identityVersion ?? null,\n\t\t\tsource_completeness:\n\t\t\t\tsource.sourceCompleteness ?? (source.lastErrorCode ? \"failed\" : \"unknown\"),\n\t\t\tlast_attempted_at: source.lastAttemptedAt ?? now,\n\t\t\tlast_error_code: source.lastErrorCode ?? null,\n\t\t\tindexed_at: now,\n\t\t\tupdated_at: now,\n\t\t};\n\t}\n\n\tprivate attemptedSourceUpdateSet(\n\t\tsource: MediaUsageSourceInput,\n\t\trow: ReturnType<MediaUsageRepository[\"buildAttemptedSourceRow\"]>,\n\t): Updateable<MediaUsageSourceTable> {\n\t\tconst updates: Updateable<MediaUsageSourceTable> = {\n\t\t\tsource_type: row.source_type,\n\t\t\tsource_variant: row.source_variant,\n\t\t\tsource_completeness: row.source_completeness,\n\t\t\tlast_attempted_at: row.last_attempted_at,\n\t\t\tlast_error_code: row.last_error_code,\n\t\t\tupdated_at: row.updated_at,\n\t\t};\n\n\t\tif (source.collectionSlug !== undefined) updates.collection_slug = row.collection_slug;\n\t\tif (source.collectionId !== undefined) updates.collection_id = row.collection_id;\n\t\tif (source.contentId !== undefined) updates.content_id = row.content_id;\n\t\tif (source.locale !== undefined) updates.locale = row.locale;\n\t\tif (source.translationGroup !== undefined) updates.translation_group = row.translation_group;\n\t\tif (source.contentSlug !== undefined) updates.content_slug = row.content_slug;\n\t\tif (source.contentTitle !== undefined) updates.content_title = row.content_title;\n\t\tif (source.contentStatus !== undefined) updates.content_status = row.content_status;\n\t\tif (source.contentScheduledAt !== undefined) {\n\t\t\tupdates.content_scheduled_at = row.content_scheduled_at;\n\t\t}\n\t\tif (source.contentDeletedAt !== undefined) updates.content_deleted_at = row.content_deleted_at;\n\t\tif (source.revisionId !== undefined) updates.revision_id = row.revision_id;\n\t\tif (source.schemaVersion !== undefined) updates.schema_version = row.schema_version;\n\t\tif (source.sourceUpdatedAt !== undefined) updates.source_updated_at = row.source_updated_at;\n\t\tif (source.sourceVersion !== undefined) updates.source_version = row.source_version;\n\t\tif (source.sourceFingerprint !== undefined) {\n\t\t\tupdates.source_fingerprint = row.source_fingerprint;\n\t\t}\n\t\tif (source.identityVersion !== undefined) updates.identity_version = row.identity_version;\n\n\t\treturn updates;\n\t}\n\n\tprivate sourceUpdateSet(\n\t\trow: ReturnType<MediaUsageRepository[\"buildSourceRow\"]>,\n\t): Updateable<MediaUsageSourceTable> {\n\t\treturn {\n\t\t\tsource_type: row.source_type,\n\t\t\tcollection_id: row.collection_id,\n\t\t\tcollection_slug: row.collection_slug,\n\t\t\tcontent_id: row.content_id,\n\t\t\tsource_variant: row.source_variant,\n\t\t\tlocale: row.locale,\n\t\t\ttranslation_group: row.translation_group,\n\t\t\tcontent_slug: row.content_slug,\n\t\t\tcontent_title: row.content_title,\n\t\t\tcontent_status: row.content_status,\n\t\t\tcontent_scheduled_at: row.content_scheduled_at,\n\t\t\tcontent_deleted_at: row.content_deleted_at,\n\t\t\trevision_id: row.revision_id,\n\t\t\tcurrent_generation: row.current_generation,\n\t\t\tschema_version: row.schema_version,\n\t\t\tsource_updated_at: row.source_updated_at,\n\t\t\tsource_version: row.source_version,\n\t\t\tsource_fingerprint: row.source_fingerprint,\n\t\t\tidentity_version: row.identity_version,\n\t\t\tsource_completeness: row.source_completeness,\n\t\t\tlast_attempted_at: row.last_attempted_at,\n\t\t\tlast_error_code: row.last_error_code,\n\t\t\tindexed_at: row.indexed_at,\n\t\t\tupdated_at: row.updated_at,\n\t\t};\n\t}\n}\n\nconst currentUsageSelect = [\n\t\"s.source_key as source_key\",\n\t\"s.source_type as source_type\",\n\t\"s.collection_id as collection_id\",\n\t\"s.collection_slug as collection_slug\",\n\t\"s.content_id as content_id\",\n\t\"s.source_variant as source_variant\",\n\t\"s.locale as locale\",\n\t\"s.translation_group as translation_group\",\n\t\"s.content_slug as content_slug\",\n\t\"s.content_title as content_title\",\n\t\"s.content_status as content_status\",\n\t\"s.content_scheduled_at as content_scheduled_at\",\n\t\"s.content_deleted_at as content_deleted_at\",\n\t\"s.revision_id as revision_id\",\n\t\"s.current_generation as current_generation\",\n\t\"s.schema_version as schema_version\",\n\t\"s.source_updated_at as source_updated_at\",\n\t\"s.source_version as source_version\",\n\t\"s.source_fingerprint as source_fingerprint\",\n\t\"s.identity_version as identity_version\",\n\t\"s.source_completeness as source_completeness\",\n\t\"s.last_attempted_at as last_attempted_at\",\n\t\"s.last_error_code as last_error_code\",\n\t\"s.indexed_at as indexed_at\",\n\t\"s.created_at as source_created_at\",\n\t\"s.updated_at as source_row_updated_at\",\n\t\"u.id as occurrence_id\",\n\t\"u.generation as generation\",\n\t\"u.field_slug as field_slug\",\n\t\"u.field_path as field_path\",\n\t\"u.occurrence_index as occurrence_index\",\n\t\"u.reference_type as reference_type\",\n\t\"u.media_id as media_id\",\n\t\"u.provider as provider\",\n\t\"u.provider_asset_id as provider_asset_id\",\n\t\"u.media_kind as media_kind\",\n\t\"u.mime_type as mime_type\",\n\t\"u.created_at as occurrence_created_at\",\n] as const;\n\nfunction groupUsageRows(rows: readonly GroupedUsageRow[]): MediaUsageEntryGroup[] {\n\tconst groups: MediaUsageEntryGroup[] = [];\n\n\tfor (const row of rows) {\n\t\tif (row.collection_slug === null || row.content_id === null) continue;\n\t\tconst record = rowToUsageRecord(row);\n\t\tlet group = groups.at(-1);\n\t\tif (\n\t\t\t!group ||\n\t\t\tgroup.collectionSlug !== row.collection_slug ||\n\t\t\tgroup.contentId !== row.content_id\n\t\t) {\n\t\t\tgroup = {\n\t\t\t\tcollectionSlug: row.collection_slug,\n\t\t\t\tcontentId: row.content_id,\n\t\t\t\tcontentDeletedAt: row.entry_deleted_at,\n\t\t\t\tsources: [],\n\t\t\t};\n\t\t\tgroups.push(group);\n\t\t}\n\n\t\tlet source = group.sources.at(-1);\n\t\tif (!source || source.source.sourceKey !== record.source.sourceKey) {\n\t\t\tsource = { source: record.source, occurrences: [] };\n\t\t\tgroup.sources.push(source);\n\t\t}\n\t\tsource.occurrences.push(record.occurrence);\n\t}\n\n\treturn groups;\n}\n\nfunction rowToSource(row: MediaUsageSourceRow): MediaUsageSource {\n\treturn {\n\t\tsourceKey: row.source_key,\n\t\tsourceType: row.source_type,\n\t\tcollectionId: row.collection_id,\n\t\tcollectionSlug: row.collection_slug,\n\t\tcontentId: row.content_id,\n\t\tsourceVariant: row.source_variant,\n\t\tlocale: row.locale,\n\t\ttranslationGroup: row.translation_group,\n\t\tcontentSlug: row.content_slug,\n\t\tcontentTitle: row.content_title,\n\t\tcontentStatus: row.content_status,\n\t\tcontentScheduledAt: row.content_scheduled_at,\n\t\tcontentDeletedAt: row.content_deleted_at,\n\t\trevisionId: row.revision_id,\n\t\tcurrentGeneration: row.current_generation,\n\t\tschemaVersion: Number(row.schema_version),\n\t\tsourceUpdatedAt: row.source_updated_at,\n\t\tsourceVersion: row.source_version === null ? null : Number(row.source_version),\n\t\tsourceFingerprint: row.source_fingerprint,\n\t\tidentityVersion: row.identity_version === null ? null : Number(row.identity_version),\n\t\tsourceCompleteness: row.source_completeness,\n\t\tlastAttemptedAt: row.last_attempted_at,\n\t\tlastErrorCode: row.last_error_code,\n\t\tindexedAt: row.indexed_at,\n\t\tcreatedAt: row.created_at,\n\t\tupdatedAt: row.updated_at,\n\t};\n}\n\nfunction rowToOccurrence(row: Selectable<MediaUsageTable>): MediaUsageOccurrence {\n\treturn {\n\t\tid: row.id,\n\t\tsourceKey: row.source_key,\n\t\tgeneration: row.generation,\n\t\tfieldSlug: row.field_slug,\n\t\tfieldPath: row.field_path,\n\t\toccurrenceIndex: Number(row.occurrence_index),\n\t\treferenceType: row.reference_type,\n\t\tmediaId: row.media_id,\n\t\tprovider: row.provider,\n\t\tproviderAssetId: row.provider_asset_id,\n\t\tmediaKind: row.media_kind,\n\t\tmimeType: row.mime_type,\n\t\tcreatedAt: row.created_at,\n\t};\n}\n\nfunction rowToUsageRecord(row: JoinedUsageRow): MediaUsageRecord {\n\treturn {\n\t\tsource: rowToSource({\n\t\t\tsource_key: row.source_key,\n\t\t\tsource_type: row.source_type,\n\t\t\tcollection_id: row.collection_id,\n\t\t\tcollection_slug: row.collection_slug,\n\t\t\tcontent_id: row.content_id,\n\t\t\tsource_variant: row.source_variant,\n\t\t\tlocale: row.locale,\n\t\t\ttranslation_group: row.translation_group,\n\t\t\tcontent_slug: row.content_slug,\n\t\t\tcontent_title: row.content_title,\n\t\t\tcontent_status: row.content_status,\n\t\t\tcontent_scheduled_at: row.content_scheduled_at,\n\t\t\tcontent_deleted_at: row.content_deleted_at,\n\t\t\trevision_id: row.revision_id,\n\t\t\tcurrent_generation: row.current_generation,\n\t\t\tschema_version: row.schema_version,\n\t\t\tsource_updated_at: row.source_updated_at,\n\t\t\tsource_version: row.source_version,\n\t\t\tsource_fingerprint: row.source_fingerprint,\n\t\t\tidentity_version: row.identity_version,\n\t\t\tsource_completeness: row.source_completeness,\n\t\t\tlast_attempted_at: row.last_attempted_at,\n\t\t\tlast_error_code: row.last_error_code,\n\t\t\tindexed_at: row.indexed_at,\n\t\t\tcreated_at: row.source_created_at,\n\t\t\tupdated_at: row.source_row_updated_at,\n\t\t}),\n\t\toccurrence: rowToOccurrence({\n\t\t\tid: row.occurrence_id,\n\t\t\tsource_key: row.source_key,\n\t\t\tgeneration: row.generation,\n\t\t\tfield_slug: row.field_slug,\n\t\t\tfield_path: row.field_path,\n\t\t\toccurrence_index: row.occurrence_index,\n\t\t\treference_type: row.reference_type,\n\t\t\tmedia_id: row.media_id,\n\t\t\tprovider: row.provider,\n\t\t\tprovider_asset_id: row.provider_asset_id,\n\t\t\tmedia_kind: row.media_kind,\n\t\t\tmime_type: row.mime_type,\n\t\t\tcreated_at: row.occurrence_created_at,\n\t\t\tcleanup_lease_token: null,\n\t\t}),\n\t};\n}\n\nfunction rowToIndexStatus(row: Selectable<MediaUsageIndexStatusTable>): MediaUsageIndexStatus {\n\treturn {\n\t\tadapterId: row.adapter_id,\n\t\tscopeType: row.scope_type,\n\t\tscopeKey: row.scope_key,\n\t\tstatus: row.status,\n\t\tschemaVersion: Number(row.schema_version),\n\t\tstartedAt: row.started_at,\n\t\tcompletedAt: row.completed_at,\n\t\tcursor: row.cursor,\n\t\tindexedSourceCount: Number(row.indexed_source_count),\n\t\tfailedSourceCount: Number(row.failed_source_count),\n\t\tlastErrorCode: row.last_error_code,\n\t\tupdatedAt: row.updated_at,\n\t};\n}\n","import type { FieldType } from \"../../schema/types.js\";\n\nexport const CONTENT_SOURCE_SCHEMA_VERSION = 1;\n\nexport type MediaKind =\n\t| \"image\"\n\t| \"video\"\n\t| \"audio\"\n\t| \"document\"\n\t| \"archive\"\n\t| \"font\"\n\t| \"text\"\n\t| \"other\";\n\nexport type MediaUsageReferenceType = \"image_field\" | \"file_field\" | \"portable_text_image\";\n\nexport interface MediaUsageExtractionSubField {\n\tslug: string;\n\ttype: FieldType;\n\tlabel?: string;\n}\n\nexport interface MediaUsageExtractionValidation {\n\tsubFields?: readonly MediaUsageExtractionSubField[];\n}\n\nexport interface MediaUsageExtractionField {\n\tslug: string;\n\ttype: FieldType;\n\tvalidation?: MediaUsageExtractionValidation | null;\n}\n\nexport interface ExtractMediaUsageOccurrencesInput {\n\tfields: readonly MediaUsageExtractionField[];\n\tdata: Record<string, unknown>;\n}\n\nexport interface ExtractedMediaUsageOccurrence {\n\tfieldSlug: string;\n\tfieldPath: string;\n\toccurrenceIndex: number;\n\treferenceType: MediaUsageReferenceType;\n\tmediaId: string | null;\n\tprovider: string;\n\tproviderAssetId: string;\n\tmediaKind: MediaKind | null;\n\tmimeType: string | null;\n}\n","import type { Kysely } from \"kysely\";\n\nimport type { Database } from \"../../database/types.js\";\nimport { validateIdentifier } from \"../../database/validate.js\";\nimport { buildCanonicalSha256Fingerprint } from \"./projection-fingerprint.js\";\nimport type { MediaUsageExtractionField, MediaUsageExtractionSubField } from \"./types.js\";\nimport { CONTENT_SOURCE_SCHEMA_VERSION } from \"./types.js\";\n\nexport type ContentMediaUsageField = MediaUsageExtractionField;\n\nexport interface ContentMediaUsageFieldDiscovery {\n\textractionFields: ContentMediaUsageField[];\n\tdisplayFieldSlugs: string[];\n}\n\nexport async function buildContentMediaUsageFieldFingerprint(\n\tdiscovery: ContentMediaUsageFieldDiscovery,\n): Promise<string> {\n\tconst extractionFields = discovery.extractionFields\n\t\t.map((field) => ({\n\t\t\tslug: field.slug,\n\t\t\ttype: field.type,\n\t\t\t...(field.type === \"repeater\"\n\t\t\t\t? {\n\t\t\t\t\t\tsubFields: (field.validation?.subFields ?? [])\n\t\t\t\t\t\t\t.map((subField) => ({ slug: subField.slug, type: subField.type }))\n\t\t\t\t\t\t\t.toSorted(compareFieldIdentity),\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t}))\n\t\t.toSorted(compareFieldIdentity);\n\tconst result = await buildCanonicalSha256Fingerprint(\"media-usage-fields:v1:sha256:\", {\n\t\tfingerprintVersion: 1,\n\t\tcontentSourceSchemaVersion: CONTENT_SOURCE_SCHEMA_VERSION,\n\t\textractionFields,\n\t\tdisplayFieldSlugs: discovery.displayFieldSlugs.toSorted(compareStrings),\n\t});\n\treturn result.fingerprint;\n}\n\nexport class MediaUsageFieldDiscoveryError extends Error {\n\tconstructor(\n\t\tmessage: string,\n\t\tpublic code: \"INVALID_REPEATER_VALIDATION\",\n\t) {\n\t\tsuper(message);\n\t\tthis.name = \"MediaUsageFieldDiscoveryError\";\n\t}\n}\n\ninterface FieldDiscoveryRow {\n\tslug: string;\n\ttype: string;\n\tvalidation: string | null;\n}\n\nconst DISPLAY_FIELD_SLUGS = [\"title\", \"name\"] as const;\nconst SUPPORTED_TOP_LEVEL_TYPES = [\"file\", \"image\", \"portableText\"] as const;\n\ntype SupportedTopLevelType = (typeof SUPPORTED_TOP_LEVEL_TYPES)[number];\n\nexport async function loadContentMediaUsageFields(\n\tdb: Kysely<Database>,\n\tcollectionSlug: string,\n\tcollectionId?: string,\n): Promise<ContentMediaUsageFieldDiscovery> {\n\tvalidateIdentifier(collectionSlug, \"collection slug\");\n\n\tlet query = db\n\t\t.selectFrom(\"_emdash_fields\")\n\t\t.innerJoin(\"_emdash_collections\", \"_emdash_collections.id\", \"_emdash_fields.collection_id\")\n\t\t.select([\"_emdash_fields.slug\", \"_emdash_fields.type\", \"_emdash_fields.validation\"])\n\t\t.where(\"_emdash_collections.slug\", \"=\", collectionSlug);\n\tif (collectionId !== undefined) query = query.where(\"_emdash_collections.id\", \"=\", collectionId);\n\tconst rows = await query.execute();\n\n\tconst extractionFields: ContentMediaUsageField[] = [];\n\tconst rowBySlug = new Map<string, FieldDiscoveryRow>();\n\n\tfor (const row of rows) {\n\t\trowBySlug.set(row.slug, row);\n\t\tif (isSupportedTopLevelType(row.type)) {\n\t\t\tvalidateIdentifier(row.slug, \"media usage field slug\");\n\t\t\textractionFields.push({ slug: row.slug, type: row.type });\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (row.type === \"repeater\") {\n\t\t\tvalidateIdentifier(row.slug, \"media usage field slug\");\n\t\t\tconst subFields = normalizeRepeaterImageSubFields(row.validation);\n\t\t\tif (subFields.length > 0) {\n\t\t\t\textractionFields.push({\n\t\t\t\t\tslug: row.slug,\n\t\t\t\t\ttype: \"repeater\",\n\t\t\t\t\tvalidation: { subFields },\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\n\textractionFields.sort((a, b) => a.slug.localeCompare(b.slug));\n\n\treturn {\n\t\textractionFields,\n\t\tdisplayFieldSlugs: DISPLAY_FIELD_SLUGS.filter((slug) => {\n\t\t\tif (!rowBySlug.has(slug)) return false;\n\t\t\tvalidateIdentifier(slug, \"media usage display field slug\");\n\t\t\treturn true;\n\t\t}),\n\t};\n}\n\nfunction normalizeRepeaterImageSubFields(\n\trawValidation: string | null,\n): MediaUsageExtractionSubField[] {\n\tconst validation = parseValidation(rawValidation);\n\tif (!isRecord(validation) || !Array.isArray(validation.subFields)) return [];\n\n\tconst subFields: MediaUsageExtractionSubField[] = [];\n\tfor (const subField of validation.subFields) {\n\t\tif (!isRecord(subField) || subField.type !== \"image\") continue;\n\t\tif (typeof subField.slug !== \"string\") continue;\n\t\tvalidateIdentifier(subField.slug, \"media usage repeater sub-field slug\");\n\t\tsubFields.push({ slug: subField.slug, type: \"image\" });\n\t}\n\n\treturn subFields.toSorted((a, b) => a.slug.localeCompare(b.slug));\n}\n\nfunction parseValidation(rawValidation: string | null): unknown {\n\tif (!rawValidation) return null;\n\ttry {\n\t\treturn JSON.parse(rawValidation);\n\t} catch {\n\t\tthrow new MediaUsageFieldDiscoveryError(\n\t\t\t\"Repeater field validation must be valid JSON before media usage can be discovered\",\n\t\t\t\"INVALID_REPEATER_VALIDATION\",\n\t\t);\n\t}\n}\n\nfunction isSupportedTopLevelType(value: string): value is SupportedTopLevelType {\n\treturn (SUPPORTED_TOP_LEVEL_TYPES as readonly string[]).includes(value);\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction compareFieldIdentity(a: { slug: string }, b: { slug: string }): number {\n\treturn compareStrings(a.slug, b.slug);\n}\n\nfunction compareStrings(a: string, b: string): number {\n\treturn a < b ? -1 : a > b ? 1 : 0;\n}\n","import { normalizeMime } from \"../mime.js\";\nimport { INTERNAL_MEDIA_PREFIX } from \"../normalize.js\";\nimport type {\n\tExtractedMediaUsageOccurrence,\n\tExtractMediaUsageOccurrencesInput,\n\tMediaKind,\n\tMediaUsageExtractionSubField,\n\tMediaUsageReferenceType,\n} from \"./types.js\";\n\nconst URL_LIKE_RE = /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i;\n\ninterface MediaRef {\n\tmediaId: string | null;\n\tprovider: string;\n\tproviderAssetId: string;\n\tmediaKind: MediaKind | null;\n\tmimeType: string | null;\n}\n\ninterface AddOccurrenceInput {\n\tfieldSlug: string;\n\tfieldPath: string;\n\treferenceType: MediaUsageReferenceType;\n\tvalue: unknown;\n\tfallbackKind: MediaKind | null;\n}\n\nexport function extractMediaUsageOccurrences({\n\tfields,\n\tdata,\n}: ExtractMediaUsageOccurrencesInput): ExtractedMediaUsageOccurrence[] {\n\tconst occurrences: ExtractedMediaUsageOccurrence[] = [];\n\tconst seen = new Set<string>();\n\n\tfor (const field of fields) {\n\t\tconst value = data[field.slug];\n\n\t\tif (field.type === \"image\") {\n\t\t\taddOccurrence(occurrences, seen, {\n\t\t\t\tfieldSlug: field.slug,\n\t\t\t\tfieldPath: field.slug,\n\t\t\t\treferenceType: \"image_field\",\n\t\t\t\tvalue,\n\t\t\t\tfallbackKind: \"image\",\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (field.type === \"file\") {\n\t\t\taddOccurrence(occurrences, seen, {\n\t\t\t\tfieldSlug: field.slug,\n\t\t\t\tfieldPath: field.slug,\n\t\t\t\treferenceType: \"file_field\",\n\t\t\t\tvalue,\n\t\t\t\tfallbackKind: null,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (field.type === \"repeater\") {\n\t\t\textractRepeaterOccurrences(occurrences, seen, field.slug, value, field.validation?.subFields);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (field.type === \"portableText\") {\n\t\t\textractPortableTextOccurrences(occurrences, seen, field.slug, value);\n\t\t}\n\t}\n\n\treturn occurrences;\n}\n\nfunction extractRepeaterOccurrences(\n\toccurrences: ExtractedMediaUsageOccurrence[],\n\tseen: Set<string>,\n\tfieldSlug: string,\n\tvalue: unknown,\n\tsubFields: readonly MediaUsageExtractionSubField[] | undefined,\n): void {\n\tif (!Array.isArray(value) || !Array.isArray(subFields)) return;\n\n\tfor (const [itemIndex, item] of value.entries()) {\n\t\tif (!isRecord(item)) continue;\n\n\t\tfor (const subField of subFields) {\n\t\t\tif (subField.type !== \"image\") continue;\n\n\t\t\taddOccurrence(occurrences, seen, {\n\t\t\t\tfieldSlug,\n\t\t\t\tfieldPath: `${fieldSlug}[${itemIndex}].${subField.slug}`,\n\t\t\t\treferenceType: \"image_field\",\n\t\t\t\tvalue: item[subField.slug],\n\t\t\t\tfallbackKind: \"image\",\n\t\t\t});\n\t\t}\n\t}\n}\n\nfunction extractPortableTextOccurrences(\n\toccurrences: ExtractedMediaUsageOccurrence[],\n\tseen: Set<string>,\n\tfieldSlug: string,\n\tvalue: unknown,\n): void {\n\tif (!Array.isArray(value)) return;\n\n\tfor (const [blockIndex, block] of value.entries()) {\n\t\tif (!isRecord(block) || block._type !== \"image\" || !isRecord(block.asset)) continue;\n\n\t\tconst provider = normalizeProvider(block.asset.provider);\n\t\tconst ref = readPortableTextAssetRef(block.asset, provider);\n\t\tif (!ref) continue;\n\n\t\taddRefOccurrence(occurrences, seen, {\n\t\t\tfieldSlug,\n\t\t\tfieldPath: `${fieldSlug}[${blockIndex}].asset.${ref.key}`,\n\t\t\treferenceType: \"portable_text_image\",\n\t\t\tref: buildMediaRef({\n\t\t\t\tid: ref.id,\n\t\t\t\tprovider,\n\t\t\t\tmimeType: normalizeMimeValue(block.asset.mimeType),\n\t\t\t\tfallbackKind: \"image\",\n\t\t\t}),\n\t\t});\n\t}\n}\n\nfunction addOccurrence(\n\toccurrences: ExtractedMediaUsageOccurrence[],\n\tseen: Set<string>,\n\tinput: AddOccurrenceInput,\n): void {\n\tconst ref = readMediaRef(input.value, input.fallbackKind);\n\tif (!ref) return;\n\n\taddRefOccurrence(occurrences, seen, {\n\t\tfieldSlug: input.fieldSlug,\n\t\tfieldPath: input.fieldPath,\n\t\treferenceType: input.referenceType,\n\t\tref,\n\t});\n}\n\nfunction addRefOccurrence(\n\toccurrences: ExtractedMediaUsageOccurrence[],\n\tseen: Set<string>,\n\tinput: {\n\t\tfieldSlug: string;\n\t\tfieldPath: string;\n\t\treferenceType: MediaUsageReferenceType;\n\t\tref: MediaRef | null;\n\t},\n): void {\n\tif (!input.ref) return;\n\n\tconst occurrence: ExtractedMediaUsageOccurrence = {\n\t\tfieldSlug: input.fieldSlug,\n\t\tfieldPath: input.fieldPath,\n\t\toccurrenceIndex: 0,\n\t\treferenceType: input.referenceType,\n\t\tmediaId: input.ref.mediaId,\n\t\tprovider: input.ref.provider,\n\t\tproviderAssetId: input.ref.providerAssetId,\n\t\tmediaKind: input.ref.mediaKind,\n\t\tmimeType: input.ref.mimeType,\n\t};\n\n\tconst key = [\n\t\toccurrence.fieldSlug,\n\t\toccurrence.fieldPath,\n\t\toccurrence.occurrenceIndex,\n\t\toccurrence.referenceType,\n\t\toccurrence.provider,\n\t\toccurrence.providerAssetId,\n\t\toccurrence.mediaId ?? \"\",\n\t].join(\"\\0\");\n\n\tif (seen.has(key)) return;\n\tseen.add(key);\n\toccurrences.push(occurrence);\n}\n\nfunction readMediaRef(value: unknown, fallbackKind: MediaKind | null): MediaRef | null {\n\tif (typeof value === \"string\") {\n\t\tconst id = normalizeLocalMediaId(value);\n\t\treturn id ? buildMediaRef({ id, provider: \"local\", mimeType: null, fallbackKind }) : null;\n\t}\n\n\tif (!isRecord(value)) return null;\n\n\tconst provider = normalizeProvider(value.provider);\n\tconst id = provider === \"local\" ? normalizeLocalMediaId(value.id) : normalizeStableId(value.id);\n\tif (!id) return null;\n\n\treturn buildMediaRef({\n\t\tid,\n\t\tprovider,\n\t\tmimeType: normalizeMimeValue(value.mimeType),\n\t\tfallbackKind,\n\t});\n}\n\nfunction buildMediaRef(input: {\n\tid: string;\n\tprovider: string;\n\tmimeType: string | null;\n\tfallbackKind: MediaKind | null;\n}): MediaRef | null {\n\tconst provider = normalizeProvider(input.provider);\n\tif (provider === \"external\") return null;\n\n\treturn {\n\t\tmediaId: provider === \"local\" ? input.id : null,\n\t\tprovider,\n\t\tproviderAssetId: input.id,\n\t\tmediaKind: mediaKindFromMime(input.mimeType) ?? input.fallbackKind,\n\t\tmimeType: input.mimeType,\n\t};\n}\n\nfunction readPortableTextAssetRef(\n\tasset: Record<string, unknown>,\n\tprovider: string,\n): { key: \"_ref\" | \"id\"; id: string } | null {\n\tconst normalizeId = provider === \"local\" ? normalizeLocalMediaId : normalizeStableId;\n\tconst ref = normalizeId(asset._ref);\n\tif (ref) return { key: \"_ref\", id: ref };\n\n\tconst id = normalizeId(asset.id);\n\tif (id) return { key: \"id\", id };\n\n\treturn null;\n}\n\nfunction normalizeProvider(value: unknown): string {\n\tconst provider = readString(value)?.trim();\n\treturn provider || \"local\";\n}\n\nfunction normalizeLocalMediaId(value: unknown): string | null {\n\tconst id = normalizeStableId(value);\n\tif (!id) return null;\n\treturn id.includes(\"/\") ? null : id;\n}\n\nfunction normalizeStableId(value: unknown): string | null {\n\tif (typeof value !== \"string\") return null;\n\tconst trimmed = value.trim();\n\tif (!trimmed) return null;\n\tif (URL_LIKE_RE.test(trimmed)) return null;\n\tif (trimmed.startsWith(INTERNAL_MEDIA_PREFIX)) return null;\n\treturn trimmed;\n}\n\nfunction normalizeMimeValue(value: unknown): string | null {\n\tif (typeof value !== \"string\") return null;\n\tconst normalized = normalizeMime(value);\n\treturn normalized.includes(\"/\") ? normalized : null;\n}\n\nfunction mediaKindFromMime(mimeType: string | null): MediaKind | null {\n\tif (!mimeType) return null;\n\tif (mimeType.startsWith(\"image/\")) return \"image\";\n\tif (mimeType.startsWith(\"video/\")) return \"video\";\n\tif (mimeType.startsWith(\"audio/\")) return \"audio\";\n\tif (mimeType.startsWith(\"font/\") || mimeType.startsWith(\"application/font-\")) return \"font\";\n\tif (mimeType.startsWith(\"text/\")) return \"text\";\n\tif (isDocumentMime(mimeType)) return \"document\";\n\tif (isArchiveMime(mimeType)) return \"archive\";\n\treturn \"other\";\n}\n\nfunction isDocumentMime(mimeType: string): boolean {\n\treturn (\n\t\tmimeType === \"application/pdf\" ||\n\t\tmimeType === \"application/msword\" ||\n\t\tmimeType === \"application/rtf\" ||\n\t\tmimeType === \"application/vnd.ms-excel\" ||\n\t\tmimeType === \"application/vnd.ms-powerpoint\" ||\n\t\tmimeType.startsWith(\"application/vnd.openxmlformats-officedocument.\")\n\t);\n}\n\nfunction isArchiveMime(mimeType: string): boolean {\n\treturn (\n\t\tmimeType === \"application/zip\" ||\n\t\tmimeType === \"application/gzip\" ||\n\t\tmimeType === \"application/x-tar\" ||\n\t\tmimeType === \"application/x-7z-compressed\" ||\n\t\tmimeType === \"application/x-rar-compressed\" ||\n\t\tmimeType === \"application/vnd.rar\"\n\t);\n}\n\nfunction readString(value: unknown): string | null {\n\treturn typeof value === \"string\" ? value : null;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n","export const MEDIA_USAGE_CONTENT_SOURCE_VARIANTS = [\"columns\", \"draft_overlay\"] as const;\n\nexport type MediaUsageContentSourceVariant = (typeof MEDIA_USAGE_CONTENT_SOURCE_VARIANTS)[number];\n\nexport interface ContentMediaUsageSourceKeyInput {\n\tcollectionId?: string;\n\tcollectionSlug: string;\n\tcontentId: string;\n\tsourceVariant: MediaUsageContentSourceVariant;\n}\n\nexport function isMediaUsageContentSourceVariant(\n\tvalue: unknown,\n): value is MediaUsageContentSourceVariant {\n\treturn (\n\t\ttypeof value === \"string\" &&\n\t\t(MEDIA_USAGE_CONTENT_SOURCE_VARIANTS as readonly string[]).includes(value)\n\t);\n}\n\nexport function buildContentMediaUsageSourceKey(input: ContentMediaUsageSourceKeyInput): string {\n\tif (input.collectionId) {\n\t\treturn `content:${input.collectionId}:${input.contentId}:${input.sourceVariant}`;\n\t}\n\treturn `content:${input.collectionSlug}:${input.contentId}:${input.sourceVariant}`;\n}\n","import { sql, type Kysely } from \"kysely\";\n\nimport type {\n\tMediaUsageOccurrenceInput,\n\tMediaUsageSourceInput,\n} from \"../../database/repositories/media-usage.js\";\nimport type { Database } from \"../../database/types.js\";\nimport { validateIdentifier } from \"../../database/validate.js\";\nimport {\n\tloadContentMediaUsageFields,\n\ttype ContentMediaUsageField,\n\ttype ContentMediaUsageFieldDiscovery,\n} from \"./content-fields.js\";\nimport { extractMediaUsageOccurrences } from \"./extractor.js\";\nimport { buildMediaUsageProjectionFingerprint } from \"./projection-fingerprint.js\";\nimport {\n\tbuildContentMediaUsageSourceKey,\n\ttype MediaUsageContentSourceVariant,\n} from \"./source-key.js\";\nimport { CONTENT_SOURCE_SCHEMA_VERSION } from \"./types.js\";\n\nexport { CONTENT_SOURCE_SCHEMA_VERSION } from \"./types.js\";\nconst CONTENT_COLLECTION_ID_RESULT = \"__emdash_media_usage_collection_id\";\n\nconst CONTENT_SYSTEM_COLUMNS = [\n\t\"id\",\n\t\"slug\",\n\t\"status\",\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] as const;\n\nexport type LoadContentMediaUsageSnapshotsResult =\n\t| { success: true; snapshots: ContentMediaUsageSnapshot[] }\n\t| {\n\t\t\tsuccess: false;\n\t\t\terror:\n\t\t\t\t| \"CONTENT_NOT_FOUND\"\n\t\t\t\t| \"DRAFT_REVISION_NOT_FOUND\"\n\t\t\t\t| \"DRAFT_REVISION_MISMATCH\"\n\t\t\t\t| \"DRAFT_REVISION_INVALID\";\n\t\t\tsource?: MediaUsageSourceInput;\n\t\t\tsnapshots?: ContentMediaUsageSnapshot[];\n\t  };\n\nexport interface ContentMediaUsageSnapshot {\n\tsource: MediaUsageSourceInput;\n\toccurrences: MediaUsageOccurrenceInput[];\n\tfields: readonly ContentMediaUsageField[];\n\tprojectionByteLength: number;\n}\n\nexport interface LoadContentMediaUsageSnapshotsOptions {\n\tcollectionId?: string;\n\tidentityVersion?: number;\n}\n\nexport async function loadContentMediaUsageSnapshots(\n\tdb: Kysely<Database>,\n\tcollectionSlug: string,\n\tcontentId: string,\n\tfieldDiscovery?: ContentMediaUsageFieldDiscovery,\n\toptions: LoadContentMediaUsageSnapshotsOptions = {},\n): Promise<LoadContentMediaUsageSnapshotsResult> {\n\tvalidateIdentifier(collectionSlug, \"collection slug\");\n\tif (options.identityVersion !== undefined && !options.collectionId) {\n\t\tthrow new Error(\"Canonical media usage snapshots require a collection identity\");\n\t}\n\tconst discovery = fieldDiscovery ?? (await loadContentMediaUsageFields(db, collectionSlug));\n\tconst row = await loadContentRow(\n\t\tdb,\n\t\tcollectionSlug,\n\t\tcontentId,\n\t\t[...discovery.extractionFields.map((field) => field.slug), ...discovery.displayFieldSlugs],\n\t\toptions.collectionId,\n\t);\n\n\tif (!row) return { success: false, error: \"CONTENT_NOT_FOUND\" };\n\tconst collectionId = readString(row[CONTENT_COLLECTION_ID_RESULT]);\n\tif (!collectionId) {\n\t\tthrow new Error(\"Media usage snapshot query did not return a collection identity\");\n\t}\n\n\tconst columnsData = projectData(\n\t\trow,\n\t\tdiscovery.extractionFields.map((field) => field.slug),\n\t);\n\tconst displayData = projectRawData(row, discovery.displayFieldSlugs);\n\tconst occurrences = extractMediaUsageOccurrences({\n\t\tfields: discovery.extractionFields,\n\t\tdata: columnsData,\n\t});\n\tconst columnsRevisionId = readNullableString(row.live_revision_id);\n\tconst columnsSource = buildContentSource({\n\t\tcollectionId: options.collectionId,\n\t\tcollectionSlug,\n\t\tidentityVersion: options.identityVersion,\n\t\trow,\n\t\tdisplayData,\n\t\tsourceVariant: \"columns\",\n\t\trevisionId: columnsRevisionId,\n\t});\n\tconst columnsProjection = await buildMediaUsageProjectionFingerprint({\n\t\tcollectionId,\n\t\tsource: columnsSource,\n\t\toccurrences,\n\t\textractionFields: discovery.extractionFields,\n\t});\n\tcolumnsSource.sourceFingerprint = columnsProjection.fingerprint;\n\tconst snapshots: ContentMediaUsageSnapshot[] = [\n\t\t{\n\t\t\tsource: columnsSource,\n\t\t\toccurrences,\n\t\t\tfields: discovery.extractionFields,\n\t\t\tprojectionByteLength: columnsProjection.byteLength,\n\t\t},\n\t];\n\n\tconst draftRevisionId = readNullableString(row.draft_revision_id);\n\tif (draftRevisionId) {\n\t\tconst attemptedDraftSource = buildContentSource({\n\t\t\tcollectionId: options.collectionId,\n\t\t\tcollectionSlug,\n\t\t\tidentityVersion: options.identityVersion,\n\t\t\trow,\n\t\t\tdisplayData,\n\t\t\tsourceVariant: \"draft_overlay\",\n\t\t\trevisionId: draftRevisionId,\n\t\t});\n\t\tconst revisionResult = await loadRevisionRow(db, draftRevisionId);\n\t\tif (!revisionResult) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: \"DRAFT_REVISION_NOT_FOUND\",\n\t\t\t\tsource: attemptedDraftSource,\n\t\t\t\tsnapshots,\n\t\t\t};\n\t\t}\n\t\tif (!revisionResult.success) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: \"DRAFT_REVISION_INVALID\",\n\t\t\t\tsource: attemptedDraftSource,\n\t\t\t\tsnapshots,\n\t\t\t};\n\t\t}\n\t\tconst revision = revisionResult.revision;\n\t\tif (revision.collection !== collectionSlug || revision.entryId !== row.id) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: \"DRAFT_REVISION_MISMATCH\",\n\t\t\t\tsource: attemptedDraftSource,\n\t\t\t\tsnapshots,\n\t\t\t};\n\t\t}\n\n\t\tconst revisionData = stripRevisionMetadata(revision.data);\n\t\tconst draftOverlayData = { ...columnsData, ...revisionData };\n\t\tconst draftDisplayData = {\n\t\t\t...displayData,\n\t\t\t...projectPresentData(revisionData, discovery.displayFieldSlugs),\n\t\t};\n\t\tconst draftContentSlug =\n\t\t\treadNullableString(revision.data._slug) ?? readNullableString(row.slug);\n\t\tconst draftOccurrences = extractMediaUsageOccurrences({\n\t\t\tfields: discovery.extractionFields,\n\t\t\tdata: draftOverlayData,\n\t\t});\n\t\tconst draftSource = buildContentSource({\n\t\t\tcollectionId: options.collectionId,\n\t\t\tcollectionSlug,\n\t\t\tidentityVersion: options.identityVersion,\n\t\t\trow,\n\t\t\tdisplayData: draftDisplayData,\n\t\t\tsourceVariant: \"draft_overlay\",\n\t\t\trevisionId: draftRevisionId,\n\t\t\tcontentSlug: draftContentSlug,\n\t\t});\n\t\tconst draftProjection = await buildMediaUsageProjectionFingerprint({\n\t\t\tcollectionId,\n\t\t\tsource: draftSource,\n\t\t\toccurrences: draftOccurrences,\n\t\t\textractionFields: discovery.extractionFields,\n\t\t});\n\t\tdraftSource.sourceFingerprint = draftProjection.fingerprint;\n\t\tsnapshots.push({\n\t\t\tsource: draftSource,\n\t\t\toccurrences: draftOccurrences,\n\t\t\tfields: discovery.extractionFields,\n\t\t\tprojectionByteLength: draftProjection.byteLength,\n\t\t});\n\t}\n\n\treturn {\n\t\tsuccess: true,\n\t\tsnapshots,\n\t};\n}\n\ninterface RevisionSnapshotRow {\n\tid: string;\n\tcollection: string;\n\tentryId: string;\n\tdata: Record<string, unknown>;\n}\n\nasync function loadContentRow(\n\tdb: Kysely<Database>,\n\tcollectionSlug: string,\n\tcontentId: string,\n\tfieldSlugs: readonly string[],\n\texpectedCollectionId?: string,\n): Promise<Record<string, unknown> | null> {\n\tconst tableName = getContentTableName(collectionSlug);\n\tconst columns = uniqueColumns([...CONTENT_SYSTEM_COLUMNS, ...fieldSlugs]);\n\tconst columnRefs = columns.map((column) => sql.ref(`content.${column}`));\n\tconst result = await sql<Record<string, unknown>>`\n\t\tSELECT\n\t\t\t${sql.join(columnRefs, sql`, `)},\n\t\t\tcollection.id AS __emdash_media_usage_collection_id\n\t\tFROM ${sql.ref(tableName)} AS content\n\t\tINNER JOIN _emdash_collections AS collection\n\t\t\tON collection.slug = ${collectionSlug}\n\t\t\t${expectedCollectionId ? sql`AND collection.id = ${expectedCollectionId}` : sql``}\n\t\tWHERE content.id = ${contentId}\n\t\tLIMIT 1\n\t`.execute(db);\n\n\treturn result.rows[0] ?? null;\n}\n\nasync function loadRevisionRow(\n\tdb: Kysely<Database>,\n\trevisionId: string,\n): Promise<{ success: true; revision: RevisionSnapshotRow } | { success: false } | null> {\n\tconst row = await db\n\t\t.selectFrom(\"revisions\")\n\t\t.select([\"id\", \"collection\", \"entry_id\", \"data\"])\n\t\t.where(\"id\", \"=\", revisionId)\n\t\t.executeTakeFirst();\n\tif (!row) return null;\n\tconst data = parseRevisionData(row.data);\n\tif (!data) return { success: false };\n\treturn {\n\t\tsuccess: true,\n\t\trevision: {\n\t\t\tid: row.id,\n\t\t\tcollection: row.collection,\n\t\t\tentryId: row.entry_id,\n\t\t\tdata,\n\t\t},\n\t};\n}\n\nfunction buildContentSource(input: {\n\tcollectionId?: string;\n\tcollectionSlug: string;\n\tidentityVersion?: number;\n\trow: Record<string, unknown>;\n\tdisplayData: Record<string, unknown>;\n\tsourceVariant: MediaUsageContentSourceVariant;\n\trevisionId: string | null;\n\tcontentSlug?: string | null;\n}): MediaUsageSourceInput {\n\tconst {\n\t\tcollectionId,\n\t\tcollectionSlug,\n\t\tidentityVersion,\n\t\trow,\n\t\tdisplayData,\n\t\tsourceVariant,\n\t\trevisionId,\n\t} = input;\n\tconst contentId = readString(row.id) ?? \"\";\n\tconst contentSlug = input.contentSlug ?? readNullableString(row.slug);\n\tconst source: MediaUsageSourceInput = {\n\t\tsourceKey: buildContentMediaUsageSourceKey({\n\t\t\tcollectionId,\n\t\t\tcollectionSlug,\n\t\t\tcontentId,\n\t\t\tsourceVariant,\n\t\t}),\n\t\tsourceType: \"content\",\n\t\tcollectionId,\n\t\tcollectionSlug,\n\t\tcontentId,\n\t\tsourceVariant,\n\t\tlocale: readNullableString(row.locale),\n\t\ttranslationGroup: readNullableString(row.translation_group),\n\t\tcontentSlug,\n\t\tcontentTitle: deriveContentTitle(displayData, contentSlug, contentId),\n\t\tcontentStatus: readNullableString(row.status),\n\t\tcontentScheduledAt: readNullableString(row.scheduled_at),\n\t\tcontentDeletedAt: readNullableString(row.deleted_at),\n\t\trevisionId,\n\t\tschemaVersion: CONTENT_SOURCE_SCHEMA_VERSION,\n\t\tsourceUpdatedAt: readNullableString(row.updated_at),\n\t\tsourceVersion: readNumber(row.version),\n\t\tidentityVersion,\n\t};\n\treturn source;\n}\n\nfunction projectData(\n\trow: Record<string, unknown>,\n\tfieldSlugs: readonly string[],\n): Record<string, unknown> {\n\tconst data: Record<string, unknown> = {};\n\tfor (const fieldSlug of fieldSlugs) {\n\t\tdata[fieldSlug] = deserializeValue(row[fieldSlug] ?? null);\n\t}\n\treturn data;\n}\n\nfunction projectRawData(\n\trow: Record<string, unknown>,\n\tfieldSlugs: readonly string[],\n): Record<string, unknown> {\n\tconst data: Record<string, unknown> = {};\n\tfor (const fieldSlug of fieldSlugs) {\n\t\tdata[fieldSlug] = row[fieldSlug] ?? null;\n\t}\n\treturn data;\n}\n\nfunction projectPresentData(\n\trow: Record<string, unknown>,\n\tfieldSlugs: readonly string[],\n): Record<string, unknown> {\n\tconst data: Record<string, unknown> = {};\n\tfor (const fieldSlug of fieldSlugs) {\n\t\tif (Object.hasOwn(row, fieldSlug)) data[fieldSlug] = row[fieldSlug];\n\t}\n\treturn data;\n}\n\nfunction uniqueColumns(columns: readonly string[]): string[] {\n\tconst unique = [...new Set(columns)];\n\tfor (const column of unique) validateIdentifier(column, \"content media usage column\");\n\treturn unique;\n}\n\nfunction getContentTableName(collectionSlug: string): string {\n\tvalidateIdentifier(collectionSlug, \"collection slug\");\n\treturn `ec_${collectionSlug}`;\n}\n\nfunction deserializeValue(value: unknown): unknown {\n\tif (typeof value === \"string\" && (value.startsWith(\"{\") || value.startsWith(\"[\"))) {\n\t\ttry {\n\t\t\treturn JSON.parse(value);\n\t\t} catch {\n\t\t\treturn value;\n\t\t}\n\t}\n\treturn value;\n}\n\nfunction parseRevisionData(value: unknown): Record<string, unknown> | null {\n\tif (typeof value === \"string\") {\n\t\ttry {\n\t\t\tconst parsed: unknown = JSON.parse(value);\n\t\t\treturn isRecord(parsed) ? parsed : null;\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\treturn isRecord(value) ? value : null;\n}\n\nfunction stripRevisionMetadata(data: Record<string, unknown>): Record<string, unknown> {\n\tconst stripped: Record<string, unknown> = {};\n\tfor (const [key, value] of Object.entries(data)) {\n\t\tif (!key.startsWith(\"_\")) stripped[key] = value;\n\t}\n\treturn stripped;\n}\n\nfunction deriveContentTitle(\n\tdisplayData: Record<string, unknown>,\n\tcontentSlug: string | null,\n\tcontentId: string,\n): string | null {\n\tfor (const fieldSlug of [\"title\", \"name\"] as const) {\n\t\tconst value = displayData[fieldSlug];\n\t\tif (typeof value === \"string\" && value.trim()) return value;\n\t}\n\treturn contentSlug ?? contentId;\n}\n\nfunction readString(value: unknown): string | null {\n\treturn typeof value === \"string\" ? value : null;\n}\n\nfunction readNullableString(value: unknown): string | null {\n\treturn value === null || value === undefined ? null : readString(value);\n}\n\nfunction readNumber(value: unknown): number | null {\n\tif (typeof value === \"number\" && Number.isFinite(value)) return value;\n\tif (typeof value === \"bigint\") return Number(value);\n\tif (typeof value === \"string\" && value) {\n\t\tconst parsed = Number(value);\n\t\treturn Number.isFinite(parsed) ? parsed : null;\n\t}\n\treturn null;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n","import { sql, type Kysely } from \"kysely\";\n\nimport { tableExists } from \"../../database/dialect-helpers.js\";\nimport {\n\tMediaUsageRepository,\n\ttype MediaUsageSource,\n} from \"../../database/repositories/media-usage.js\";\nimport type { Database } from \"../../database/types.js\";\nimport { validateIdentifier } from \"../../database/validate.js\";\nimport { isI18nEnabled } from \"../../i18n/config.js\";\nimport { loadContentMediaUsageFields } from \"./content-fields.js\";\nimport {\n\tCONTENT_SOURCE_SCHEMA_VERSION,\n\tloadContentMediaUsageSnapshots,\n\ttype ContentMediaUsageSnapshot,\n} from \"./content-snapshots.js\";\nimport {\n\tbuildContentMediaUsageSourceKey,\n\tMEDIA_USAGE_CONTENT_SOURCE_VARIANTS,\n} from \"./source-key.js\";\n\nexport const CONTENT_MEDIA_USAGE_ADAPTER_ID = \"content-media\";\nexport const CONTENT_MEDIA_USAGE_COLLECTION_SCOPE = \"collection\";\n\nconst CONTENT_USAGE_LOCKS_KEY = Symbol.for(\"emdash.mediaUsage.contentLocks\");\nconst CONTENT_USAGE_COLLECTION_LOCKS_KEY = Symbol.for(\"emdash.mediaUsage.collectionLocks\");\nconst CONTENT_USAGE_REFRESH_MAX_ATTEMPTS = 2;\n\nexport const MEDIA_USAGE_PROJECTION_ADMISSION_LIMITS = Object.freeze({\n\tmaxOccurrenceMutationUnitsPerClaim: 12,\n\tmaxProjectionMutationBytesPerClaim: 512 * 1024,\n});\n\nexport interface ContentMediaUsageAdmissionBudget {\n\tremainingOccurrenceMutationUnits: number;\n\tremainingProjectionMutationBytes: number;\n\thasReservedMutation: boolean;\n}\n\nexport type ContentMediaUsageProjectionAdmissionResult =\n\t| {\n\t\t\toutcome: \"admitted\";\n\t\t\tnoOpSourceKeys: ReadonlySet<string>;\n\t\t\tabsentSources: MediaUsageSource[];\n\t\t\toccurrenceMutationUnits: number;\n\t\t\tprojectionMutationBytes: number;\n\t  }\n\t| { outcome: \"intrinsic_resource_limit\" }\n\t| { outcome: \"claim_budget_deferred\" };\n\n// These maps only de-dupe usage work inside the current isolate/process. Cross-worker\n// correctness comes from expected-generation guards on repository writes.\n\nexport type ContentMediaUsageRefreshErrorCode =\n\t| \"CONTENT_NOT_FOUND\"\n\t| \"DRAFT_REVISION_NOT_FOUND\"\n\t| \"DRAFT_REVISION_MISMATCH\"\n\t| \"DRAFT_REVISION_INVALID\"\n\t| \"CONTENT_USAGE_REFRESH_ERROR\"\n\t| \"CONTENT_USAGE_DELETE_ERROR\"\n\t| \"CONTENT_USAGE_GENERATION_CONFLICT\"\n\t| \"CONTENT_USAGE_RESOURCE_LIMIT\"\n\t| \"CONTENT_USAGE_STALE\";\n\ninterface ContentMediaUsageRefreshOptions {\n\tcollectionId?: string;\n\tdurableWork?: boolean;\n\tadmissionBudget?: ContentMediaUsageAdmissionBudget;\n}\n\nexport interface ContentMediaUsageRefreshResult {\n\tsuccess: boolean;\n\trefreshedSourceCount: number;\n\tdeletedSourceCount: number;\n\tfailedSourceCount: number;\n\terrorCode?: ContentMediaUsageRefreshErrorCode;\n}\n\nconst ZERO_RESULT: ContentMediaUsageRefreshResult = {\n\tsuccess: true,\n\trefreshedSourceCount: 0,\n\tdeletedSourceCount: 0,\n\tfailedSourceCount: 0,\n};\n\nexport function createContentMediaUsageAdmissionBudget(): ContentMediaUsageAdmissionBudget {\n\treturn {\n\t\tremainingOccurrenceMutationUnits:\n\t\t\tMEDIA_USAGE_PROJECTION_ADMISSION_LIMITS.maxOccurrenceMutationUnitsPerClaim,\n\t\tremainingProjectionMutationBytes:\n\t\t\tMEDIA_USAGE_PROJECTION_ADMISSION_LIMITS.maxProjectionMutationBytesPerClaim,\n\t\thasReservedMutation: false,\n\t};\n}\n\nexport async function planContentMediaUsageProjectionAdmission(\n\trepo: MediaUsageRepository,\n\tsnapshots: readonly ContentMediaUsageSnapshot[],\n\tobservedSources: ReadonlyMap<string, MediaUsageSource>,\n\tcanonicalSourceKeys: readonly string[],\n\tbudget: ContentMediaUsageAdmissionBudget,\n): Promise<ContentMediaUsageProjectionAdmissionResult> {\n\tconst snapshotSourceKeys = new Set(snapshots.map((snapshot) => snapshot.source.sourceKey));\n\tconst absentSources = canonicalSourceKeys\n\t\t.filter((sourceKey) => !snapshotSourceKeys.has(sourceKey))\n\t\t.map((sourceKey) => observedSources.get(sourceKey))\n\t\t.filter((source): source is MediaUsageSource => source !== undefined);\n\tlet deletionOccurrenceUnits = 0;\n\tlet deletionBytes = 0;\n\tfor (const source of absentSources) {\n\t\tconst measurement = await repo.measureSourceGenerationDeletion(\n\t\t\tsource.sourceKey,\n\t\t\tsource.currentGeneration,\n\t\t\tMEDIA_USAGE_PROJECTION_ADMISSION_LIMITS.maxOccurrenceMutationUnitsPerClaim,\n\t\t);\n\t\tif (measurement.exceedsOccurrenceLimit) {\n\t\t\treturn budget.hasReservedMutation\n\t\t\t\t? { outcome: \"claim_budget_deferred\" }\n\t\t\t\t: { outcome: \"intrinsic_resource_limit\" };\n\t\t}\n\t\tdeletionOccurrenceUnits += measurement.occurrenceCount;\n\t\tdeletionBytes += storedMediaUsageSourceByteLength(source) + measurement.occurrenceBytes * 2;\n\t}\n\n\tconst noOpSourceKeys = new Set<string>();\n\tlet cost = projectionAdmissionCost(\n\t\tsnapshots,\n\t\tnoOpSourceKeys,\n\t\tdeletionOccurrenceUnits,\n\t\tdeletionBytes,\n\t);\n\tif (exceedsProjectionAdmissionLimits(cost)) {\n\t\tfor (const snapshot of snapshots) {\n\t\t\tconst expectedSource = observedSources.get(snapshot.source.sourceKey);\n\t\t\tif (\n\t\t\t\texpectedSource &&\n\t\t\t\t(await repo.projectionMatchesExpectedSource(snapshot.source, expectedSource))\n\t\t\t) {\n\t\t\t\tnoOpSourceKeys.add(snapshot.source.sourceKey);\n\t\t\t}\n\t\t}\n\t\tcost = projectionAdmissionCost(\n\t\t\tsnapshots,\n\t\t\tnoOpSourceKeys,\n\t\t\tdeletionOccurrenceUnits,\n\t\t\tdeletionBytes,\n\t\t);\n\t}\n\n\tif (exceedsProjectionAdmissionLimits(cost)) {\n\t\treturn budget.hasReservedMutation\n\t\t\t? { outcome: \"claim_budget_deferred\" }\n\t\t\t: { outcome: \"intrinsic_resource_limit\" };\n\t}\n\tif (\n\t\tcost.occurrenceMutationUnits > budget.remainingOccurrenceMutationUnits ||\n\t\tcost.projectionMutationBytes > budget.remainingProjectionMutationBytes\n\t) {\n\t\treturn { outcome: \"claim_budget_deferred\" };\n\t}\n\n\tbudget.remainingOccurrenceMutationUnits -= cost.occurrenceMutationUnits;\n\tbudget.remainingProjectionMutationBytes -= cost.projectionMutationBytes;\n\tif (cost.occurrenceMutationUnits > 0 || cost.projectionMutationBytes > 0) {\n\t\tbudget.hasReservedMutation = true;\n\t}\n\treturn {\n\t\toutcome: \"admitted\",\n\t\tnoOpSourceKeys,\n\t\tabsentSources,\n\t\t...cost,\n\t};\n}\n\ninterface ProjectionAdmissionCost {\n\toccurrenceMutationUnits: number;\n\tprojectionMutationBytes: number;\n}\n\nfunction projectionAdmissionCost(\n\tsnapshots: readonly ContentMediaUsageSnapshot[],\n\tnoOpSourceKeys: ReadonlySet<string>,\n\tdeletionOccurrenceUnits: number,\n\tdeletionBytes: number,\n): ProjectionAdmissionCost {\n\treturn snapshots.reduce<ProjectionAdmissionCost>(\n\t\t(cost, snapshot) => {\n\t\t\tif (noOpSourceKeys.has(snapshot.source.sourceKey)) return cost;\n\t\t\tcost.occurrenceMutationUnits += snapshot.occurrences.length;\n\t\t\tcost.projectionMutationBytes += snapshot.projectionByteLength;\n\t\t\treturn cost;\n\t\t},\n\t\t{\n\t\t\toccurrenceMutationUnits: deletionOccurrenceUnits,\n\t\t\tprojectionMutationBytes: deletionBytes,\n\t\t},\n\t);\n}\n\nfunction exceedsProjectionAdmissionLimits(cost: ProjectionAdmissionCost): boolean {\n\treturn (\n\t\tcost.occurrenceMutationUnits >\n\t\t\tMEDIA_USAGE_PROJECTION_ADMISSION_LIMITS.maxOccurrenceMutationUnitsPerClaim ||\n\t\tcost.projectionMutationBytes >\n\t\t\tMEDIA_USAGE_PROJECTION_ADMISSION_LIMITS.maxProjectionMutationBytesPerClaim\n\t);\n}\n\nfunction storedMediaUsageSourceByteLength(source: MediaUsageSource): number {\n\treturn new TextEncoder().encode(JSON.stringify(source)).byteLength;\n}\n\nexport async function refreshContentMediaUsage(\n\tdb: Kysely<Database>,\n\tcollectionSlug: string,\n\tcontentId: string,\n): Promise<ContentMediaUsageRefreshResult> {\n\tvalidateIdentifier(collectionSlug, \"collection slug\");\n\treturn withContentUsageCollectionLock(collectionSlug, () =>\n\t\twithContentUsageLock(collectionSlug, contentId, () =>\n\t\t\trefreshContentMediaUsageUnlocked(db, collectionSlug, contentId, {}),\n\t\t),\n\t);\n}\n\nexport async function refreshContentMediaUsageForWork(\n\tdb: Kysely<Database>,\n\tcollectionId: string,\n\tcollectionSlug: string,\n\tcontentId: string,\n): Promise<ContentMediaUsageRefreshResult> {\n\tvalidateIdentifier(collectionSlug, \"collection slug\");\n\tif (!collectionId) throw new Error(\"Durable media usage work requires a collection identity\");\n\treturn withContentUsageCollectionLock(collectionSlug, () =>\n\t\twithContentUsageLock(collectionSlug, contentId, () =>\n\t\t\trefreshContentMediaUsageUnlocked(db, collectionSlug, contentId, {\n\t\t\t\tcollectionId,\n\t\t\t\tdurableWork: true,\n\t\t\t}),\n\t\t),\n\t);\n}\n\nasync function refreshContentMediaUsageUnlocked(\n\tdb: Kysely<Database>,\n\tcollectionSlug: string,\n\tcontentId: string,\n\toptions: ContentMediaUsageRefreshOptions,\n): Promise<ContentMediaUsageRefreshResult> {\n\ttry {\n\t\tlet conflictResult: ContentMediaUsageRefreshResult | null = null;\n\t\tif (options.durableWork) options.admissionBudget = createContentMediaUsageAdmissionBudget();\n\t\tfor (let attempt = 0; attempt < CONTENT_USAGE_REFRESH_MAX_ATTEMPTS; attempt++) {\n\t\t\tconst result = await refreshContentMediaUsageAttempt(db, collectionSlug, contentId, options);\n\t\t\tif (result.errorCode !== \"CONTENT_USAGE_GENERATION_CONFLICT\") return result;\n\t\t\tconflictResult = result;\n\t\t\tif (options.admissionBudget?.hasReservedMutation) break;\n\t\t}\n\n\t\tif (options.durableWork) {\n\t\t\treturn generationConflictResult({\n\t\t\t\trefreshedSourceCount: conflictResult?.refreshedSourceCount ?? 0,\n\t\t\t\tdeletedSourceCount: conflictResult?.deletedSourceCount ?? 0,\n\t\t\t});\n\t\t}\n\t\treturn markGenerationConflict(db, collectionSlug, {\n\t\t\trefreshedSourceCount: conflictResult?.refreshedSourceCount ?? 0,\n\t\t\tdeletedSourceCount: conflictResult?.deletedSourceCount ?? 0,\n\t\t});\n\t} catch (error) {\n\t\tconsole.error(`[media-usage] Failed to refresh ${collectionSlug}/${contentId}:`, error);\n\t\tif (!options.durableWork) {\n\t\t\tawait markContentMediaUsageCollectionStaleSafely(\n\t\t\t\tdb,\n\t\t\t\tcollectionSlug,\n\t\t\t\t\"CONTENT_USAGE_REFRESH_ERROR\",\n\t\t\t);\n\t\t}\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\trefreshedSourceCount: 0,\n\t\t\tdeletedSourceCount: 0,\n\t\t\tfailedSourceCount: 0,\n\t\t\terrorCode: \"CONTENT_USAGE_REFRESH_ERROR\",\n\t\t};\n\t}\n}\n\nasync function refreshContentMediaUsageAttempt(\n\tdb: Kysely<Database>,\n\tcollectionSlug: string,\n\tcontentId: string,\n\toptions: ContentMediaUsageRefreshOptions,\n): Promise<ContentMediaUsageRefreshResult> {\n\tconst repo = new MediaUsageRepository(db);\n\tconst canonicalSourceKeys = contentSourceKeys(collectionSlug, contentId, options.collectionId);\n\tconst observedSources = await repo.findSources(canonicalSourceKeys);\n\tconst snapshotsResult = await loadContentMediaUsageSnapshots(\n\t\tdb,\n\t\tcollectionSlug,\n\t\tcontentId,\n\t\tundefined,\n\t\toptions.collectionId ? { collectionId: options.collectionId, identityVersion: 1 } : undefined,\n\t);\n\tif (!snapshotsResult.success) {\n\t\tif (snapshotsResult.error === \"CONTENT_NOT_FOUND\" && options.collectionId) {\n\t\t\tif (!(await contentCollectionExists(db, collectionSlug, options.collectionId))) {\n\t\t\t\treturn generationConflictResult({ refreshedSourceCount: 0, deletedSourceCount: 0 });\n\t\t\t}\n\t\t\tif (!options.admissionBudget)\n\t\t\t\tthrow new Error(\"Durable media usage work requires an admission budget\");\n\t\t\tconst admission = await planContentMediaUsageProjectionAdmission(\n\t\t\t\trepo,\n\t\t\t\t[],\n\t\t\t\tobservedSources,\n\t\t\t\tcanonicalSourceKeys,\n\t\t\t\toptions.admissionBudget,\n\t\t\t);\n\t\t\tif (admission.outcome !== \"admitted\") return admissionFailureResult(admission.outcome);\n\t\t\treturn deleteCanonicalContentSourcesIfAbsent(\n\t\t\t\trepo,\n\t\t\t\tadmission.absentSources,\n\t\t\t\tcollectionSlug,\n\t\t\t\tcontentId,\n\t\t\t);\n\t\t}\n\t\tif (\n\t\t\tsnapshotsResult.error === \"CONTENT_NOT_FOUND\" &&\n\t\t\t!(await contentCollectionExists(db, collectionSlug))\n\t\t) {\n\t\t\tconst deletedSourceCount = await repo.deleteContentSources(collectionSlug, contentId);\n\t\t\treturn { ...ZERO_RESULT, deletedSourceCount };\n\t\t}\n\t\treturn options.durableWork\n\t\t\t? snapshotFailureResult(snapshotsResult)\n\t\t\t: markSnapshotFailure(db, collectionSlug, snapshotsResult);\n\t}\n\n\tif (!(await contentCollectionExists(db, collectionSlug, options.collectionId))) {\n\t\tif (options.collectionId) {\n\t\t\treturn generationConflictResult({ refreshedSourceCount: 0, deletedSourceCount: 0 });\n\t\t}\n\t\tconst deletedSourceCount = await repo.deleteContentSources(collectionSlug, contentId);\n\t\treturn { ...ZERO_RESULT, deletedSourceCount };\n\t}\n\tconst admission = options.admissionBudget\n\t\t? await planContentMediaUsageProjectionAdmission(\n\t\t\t\trepo,\n\t\t\t\tsnapshotsResult.snapshots,\n\t\t\t\tobservedSources,\n\t\t\t\tcanonicalSourceKeys,\n\t\t\t\toptions.admissionBudget,\n\t\t\t)\n\t\t: null;\n\tif (admission && admission.outcome !== \"admitted\") {\n\t\treturn admissionFailureResult(admission.outcome);\n\t}\n\tlet refreshedSourceCount = 0;\n\tfor (const snapshot of snapshotsResult.snapshots) {\n\t\tif (\n\t\t\tadmission?.outcome === \"admitted\" &&\n\t\t\tadmission.noOpSourceKeys.has(snapshot.source.sourceKey)\n\t\t) {\n\t\t\trefreshedSourceCount++;\n\t\t\tcontinue;\n\t\t}\n\t\tconst result = await repo.replaceSourceIfMatching(\n\t\t\tsnapshot.source,\n\t\t\tsnapshot.occurrences,\n\t\t\tobservedSources.get(snapshot.source.sourceKey) ?? null,\n\t\t);\n\t\tif (result.unchanged) {\n\t\t\trefreshedSourceCount++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (!result.replaced) {\n\t\t\treturn generationConflictResult({\n\t\t\t\trefreshedSourceCount,\n\t\t\t\tdeletedSourceCount: 0,\n\t\t\t});\n\t\t}\n\t\trefreshedSourceCount++;\n\t}\n\tif (!(await contentCollectionExists(db, collectionSlug, options.collectionId))) {\n\t\tif (options.collectionId) {\n\t\t\treturn generationConflictResult({ refreshedSourceCount, deletedSourceCount: 0 });\n\t\t}\n\t\tconst deletedSourceCount = await repo.deleteContentSources(collectionSlug, contentId);\n\t\treturn { ...ZERO_RESULT, deletedSourceCount };\n\t}\n\n\tconst expectedSourceKeys = new Set(\n\t\tsnapshotsResult.snapshots.map((snapshot) => snapshot.source.sourceKey),\n\t);\n\tconst absentSources =\n\t\tadmission?.outcome === \"admitted\"\n\t\t\t? admission.absentSources\n\t\t\t: canonicalSourceKeys\n\t\t\t\t\t.filter((sourceKey) => !expectedSourceKeys.has(sourceKey))\n\t\t\t\t\t.map((sourceKey) => observedSources.get(sourceKey))\n\t\t\t\t\t.filter((source): source is MediaUsageSource => source !== undefined);\n\tlet deletedSourceCount = 0;\n\tfor (const expectedSource of absentSources) {\n\t\tconst result = await repo.deleteSourceIfMatching(expectedSource.sourceKey, expectedSource);\n\t\tif (result.deleted) {\n\t\t\tdeletedSourceCount++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (result.source) {\n\t\t\treturn generationConflictResult({\n\t\t\t\trefreshedSourceCount,\n\t\t\t\tdeletedSourceCount,\n\t\t\t});\n\t\t}\n\t}\n\n\treturn {\n\t\tsuccess: true,\n\t\trefreshedSourceCount,\n\t\tdeletedSourceCount,\n\t\tfailedSourceCount: 0,\n\t};\n}\n\nfunction contentSourceKeys(\n\tcollectionSlug: string,\n\tcontentId: string,\n\tcollectionId?: string,\n): string[] {\n\treturn MEDIA_USAGE_CONTENT_SOURCE_VARIANTS.map((sourceVariant) =>\n\t\tbuildContentMediaUsageSourceKey({\n\t\t\tcollectionId,\n\t\t\tcollectionSlug,\n\t\t\tcontentId,\n\t\t\tsourceVariant,\n\t\t}),\n\t);\n}\n\nfunction admissionFailureResult(\n\toutcome: \"intrinsic_resource_limit\" | \"claim_budget_deferred\",\n): ContentMediaUsageRefreshResult {\n\treturn {\n\t\t...generationConflictResult({ refreshedSourceCount: 0, deletedSourceCount: 0 }),\n\t\terrorCode:\n\t\t\toutcome === \"intrinsic_resource_limit\"\n\t\t\t\t? \"CONTENT_USAGE_RESOURCE_LIMIT\"\n\t\t\t\t: \"CONTENT_USAGE_GENERATION_CONFLICT\",\n\t};\n}\n\nasync function markGenerationConflict(\n\tdb: Kysely<Database>,\n\tcollectionSlug: string,\n\tcounts: Pick<ContentMediaUsageRefreshResult, \"refreshedSourceCount\" | \"deletedSourceCount\">,\n): Promise<ContentMediaUsageRefreshResult> {\n\tawait markContentMediaUsageCollectionStaleSafely(\n\t\tdb,\n\t\tcollectionSlug,\n\t\t\"CONTENT_USAGE_GENERATION_CONFLICT\",\n\t);\n\treturn {\n\t\tsuccess: false,\n\t\trefreshedSourceCount: counts.refreshedSourceCount,\n\t\tdeletedSourceCount: counts.deletedSourceCount,\n\t\tfailedSourceCount: 0,\n\t\terrorCode: \"CONTENT_USAGE_GENERATION_CONFLICT\",\n\t};\n}\n\nfunction generationConflictResult(\n\tcounts: Pick<ContentMediaUsageRefreshResult, \"refreshedSourceCount\" | \"deletedSourceCount\">,\n): ContentMediaUsageRefreshResult {\n\treturn {\n\t\tsuccess: false,\n\t\trefreshedSourceCount: counts.refreshedSourceCount,\n\t\tdeletedSourceCount: counts.deletedSourceCount,\n\t\tfailedSourceCount: 0,\n\t\terrorCode: \"CONTENT_USAGE_GENERATION_CONFLICT\",\n\t};\n}\n\nasync function contentCollectionExists(\n\tdb: Kysely<Database>,\n\tcollectionSlug: string,\n\tcollectionId?: string,\n): Promise<boolean> {\n\tlet query = db.selectFrom(\"_emdash_collections\").select(\"id\").where(\"slug\", \"=\", collectionSlug);\n\tif (collectionId) query = query.where(\"id\", \"=\", collectionId);\n\tconst row = await query.executeTakeFirst();\n\treturn row !== undefined;\n}\n\nexport async function deleteContentMediaUsage(\n\tdb: Kysely<Database>,\n\tcollectionSlug: string,\n\tcontentId: string,\n): Promise<ContentMediaUsageRefreshResult> {\n\tvalidateIdentifier(collectionSlug, \"collection slug\");\n\treturn withContentUsageCollectionLock(collectionSlug, () =>\n\t\twithContentUsageLock(collectionSlug, contentId, () =>\n\t\t\tdeleteContentMediaUsageUnlocked(db, collectionSlug, contentId),\n\t\t),\n\t);\n}\n\nasync function deleteContentMediaUsageUnlocked(\n\tdb: Kysely<Database>,\n\tcollectionSlug: string,\n\tcontentId: string,\n): Promise<ContentMediaUsageRefreshResult> {\n\ttry {\n\t\tconst deletedSourceCount = await new MediaUsageRepository(db).deleteContentSources(\n\t\t\tcollectionSlug,\n\t\t\tcontentId,\n\t\t);\n\t\treturn { ...ZERO_RESULT, deletedSourceCount };\n\t} catch (error) {\n\t\tconsole.error(\n\t\t\t`[media-usage] Failed to delete usage for ${collectionSlug}/${contentId}:`,\n\t\t\terror,\n\t\t);\n\t\tawait markContentMediaUsageCollectionStaleSafely(\n\t\t\tdb,\n\t\t\tcollectionSlug,\n\t\t\t\"CONTENT_USAGE_DELETE_ERROR\",\n\t\t);\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\trefreshedSourceCount: 0,\n\t\t\tdeletedSourceCount: 0,\n\t\t\tfailedSourceCount: 0,\n\t\t\terrorCode: \"CONTENT_USAGE_DELETE_ERROR\",\n\t\t};\n\t}\n}\n\nexport async function deleteContentMediaUsageCollection(\n\tdb: Kysely<Database>,\n\tcollectionSlug: string,\n): Promise<ContentMediaUsageRefreshResult> {\n\tvalidateIdentifier(collectionSlug, \"collection slug\");\n\treturn withContentUsageCollectionLock(collectionSlug, () =>\n\t\tdeleteContentMediaUsageCollectionUnlocked(db, collectionSlug),\n\t);\n}\n\nasync function deleteContentMediaUsageCollectionUnlocked(\n\tdb: Kysely<Database>,\n\tcollectionSlug: string,\n): Promise<ContentMediaUsageRefreshResult> {\n\ttry {\n\t\tconst repo = new MediaUsageRepository(db);\n\t\tconst deletedSourceCount = await repo.deleteCollectionSources(collectionSlug);\n\t\tawait repo.deleteIndexStatus({\n\t\t\tadapterId: CONTENT_MEDIA_USAGE_ADAPTER_ID,\n\t\t\tscopeType: CONTENT_MEDIA_USAGE_COLLECTION_SCOPE,\n\t\t\tscopeKey: collectionSlug,\n\t\t});\n\t\treturn { ...ZERO_RESULT, deletedSourceCount };\n\t} catch (error) {\n\t\tconsole.error(`[media-usage] Failed to delete usage for collection ${collectionSlug}:`, error);\n\t\ttry {\n\t\t\tawait new MediaUsageRepository(db).deleteIndexStatus({\n\t\t\t\tadapterId: CONTENT_MEDIA_USAGE_ADAPTER_ID,\n\t\t\t\tscopeType: CONTENT_MEDIA_USAGE_COLLECTION_SCOPE,\n\t\t\t\tscopeKey: collectionSlug,\n\t\t\t});\n\t\t} catch (statusError) {\n\t\t\tconsole.error(\n\t\t\t\t`[media-usage] Failed to clear usage status for deleted collection ${collectionSlug}:`,\n\t\t\t\tstatusError,\n\t\t\t);\n\t\t}\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\trefreshedSourceCount: 0,\n\t\t\tdeletedSourceCount: 0,\n\t\t\tfailedSourceCount: 0,\n\t\t\terrorCode: \"CONTENT_USAGE_DELETE_ERROR\",\n\t\t};\n\t}\n}\n\nexport async function refreshContentMediaUsageAfterWrite(\n\tdb: Kysely<Database>,\n\tcollectionSlug: string,\n\tcontentId: string,\n): Promise<void> {\n\tconst result = await refreshContentMediaUsage(db, collectionSlug, contentId);\n\tif (!result.success) {\n\t\tconsole.error(\n\t\t\t`[media-usage] Usage refresh for ${collectionSlug}/${contentId} finished with ${result.errorCode}`,\n\t\t);\n\t}\n}\n\nexport async function markContentMediaUsageCollectionStale(\n\tdb: Kysely<Database>,\n\tcollectionSlug: string,\n\tlastErrorCode: string,\n): Promise<void> {\n\tvalidateIdentifier(collectionSlug, \"collection slug\");\n\tconst repo = new MediaUsageRepository(db);\n\tconst identity = {\n\t\tadapterId: CONTENT_MEDIA_USAGE_ADAPTER_ID,\n\t\tscopeType: CONTENT_MEDIA_USAGE_COLLECTION_SCOPE,\n\t\tscopeKey: collectionSlug,\n\t};\n\tconst existing = await repo.findIndexStatus(identity);\n\tawait repo.upsertIndexStatus({\n\t\t...identity,\n\t\tstatus: \"stale\",\n\t\tschemaVersion: existing?.schemaVersion ?? CONTENT_SOURCE_SCHEMA_VERSION,\n\t\tstartedAt: existing?.startedAt ?? null,\n\t\tcompletedAt: existing?.completedAt ?? null,\n\t\tcursor: existing?.cursor ?? null,\n\t\tindexedSourceCount: existing?.indexedSourceCount ?? 0,\n\t\tfailedSourceCount: existing?.failedSourceCount ?? 0,\n\t\tlastErrorCode,\n\t});\n}\n\nexport async function invalidateContentMediaUsageSchemaChange(\n\tdb: Kysely<Database>,\n\tcollectionSlug: string,\n): Promise<boolean> {\n\tvalidateIdentifier(collectionSlug, \"collection slug\");\n\tif (!(await tableExists(db, \"_emdash_media_usage_activation\"))) return false;\n\tconst activation = await db\n\t\t.selectFrom(\"_emdash_media_usage_activation\")\n\t\t.select(\"state\")\n\t\t.where(\"task_key\", \"=\", \"incremental_capture\")\n\t\t.executeTakeFirst();\n\tif (activation?.state !== \"active\") return false;\n\n\tconst invalidated = await new MediaUsageRepository(db).invalidateIndexStatusForSchemaChange(\n\t\tcollectionSlug,\n\t);\n\tif (!invalidated) {\n\t\tthrow new Error(`Cannot invalidate media usage coverage for collection ${collectionSlug}`);\n\t}\n\treturn true;\n}\n\nexport async function findNonTranslatableSiblingContentIds(\n\tdb: Kysely<Database>,\n\tcollectionSlug: string,\n\tupdatedContentId: string,\n\ttranslationGroup: string | null | undefined,\n\tupdatedData: Record<string, unknown> | undefined,\n): Promise<string[]> {\n\tif (!isI18nEnabled() || !updatedData || !translationGroup) return [];\n\n\tvalidateIdentifier(collectionSlug, \"collection slug\");\n\tconst collection = await db\n\t\t.selectFrom(\"_emdash_collections\")\n\t\t.select(\"id\")\n\t\t.where(\"slug\", \"=\", collectionSlug)\n\t\t.executeTakeFirst();\n\tif (!collection) return [];\n\n\tconst fields = await db\n\t\t.selectFrom(\"_emdash_fields\")\n\t\t.select(\"slug\")\n\t\t.where(\"collection_id\", \"=\", collection.id)\n\t\t.where(\"translatable\", \"=\", 0)\n\t\t.execute();\n\n\tconst touchedNonTranslatableSlugs = fields\n\t\t.filter((field) => field.slug in updatedData)\n\t\t.map((field) => field.slug);\n\tif (touchedNonTranslatableSlugs.length === 0) return [];\n\n\tconst usageFields = await loadContentMediaUsageFields(db, collectionSlug);\n\tconst usageRelevantSlugs = new Set([\n\t\t...usageFields.extractionFields.map((field) => field.slug),\n\t\t...usageFields.displayFieldSlugs,\n\t]);\n\tif (!touchedNonTranslatableSlugs.some((slug) => usageRelevantSlugs.has(slug))) return [];\n\n\tconst tableName = `ec_${collectionSlug}`;\n\tconst rows = await sql<{ id: string }>`\n\t\tSELECT id\n\t\tFROM ${sql.ref(tableName)}\n\t\tWHERE translation_group = ${translationGroup}\n\t\tAND id != ${updatedContentId}\n\t\tORDER BY id ASC\n\t`.execute(db);\n\n\treturn rows.rows.map((row) => row.id);\n}\n\nasync function markSnapshotFailure(\n\tdb: Kysely<Database>,\n\tcollectionSlug: string,\n\tresult: Exclude<Awaited<ReturnType<typeof loadContentMediaUsageSnapshots>>, { success: true }>,\n): Promise<ContentMediaUsageRefreshResult> {\n\tconst repo = new MediaUsageRepository(db);\n\tif (result.source) {\n\t\tawait repo.markSourceAttempted({\n\t\t\t...result.source,\n\t\t\tsourceCompleteness: \"failed\",\n\t\t\tlastErrorCode: result.error,\n\t\t});\n\t}\n\tawait markContentMediaUsageCollectionStale(db, collectionSlug, result.error);\n\treturn {\n\t\tsuccess: false,\n\t\trefreshedSourceCount: 0,\n\t\tdeletedSourceCount: 0,\n\t\tfailedSourceCount: result.source ? 1 : 0,\n\t\terrorCode: result.error,\n\t};\n}\n\nfunction snapshotFailureResult(\n\tresult: Exclude<Awaited<ReturnType<typeof loadContentMediaUsageSnapshots>>, { success: true }>,\n): ContentMediaUsageRefreshResult {\n\treturn {\n\t\tsuccess: false,\n\t\trefreshedSourceCount: 0,\n\t\tdeletedSourceCount: 0,\n\t\tfailedSourceCount: result.source ? 1 : 0,\n\t\terrorCode: result.error,\n\t};\n}\n\nasync function deleteCanonicalContentSourcesIfAbsent(\n\trepo: MediaUsageRepository,\n\tobservedSources: readonly MediaUsageSource[],\n\tcollectionSlug: string,\n\tcontentId: string,\n): Promise<ContentMediaUsageRefreshResult> {\n\tlet deletedSourceCount = 0;\n\tfor (const source of observedSources) {\n\t\tconst result = await repo.deleteSourceIfMatchingContentAbsent(\n\t\t\tsource.sourceKey,\n\t\t\tsource,\n\t\t\tcollectionSlug,\n\t\t\tcontentId,\n\t\t);\n\t\tif (result.deleted) {\n\t\t\tdeletedSourceCount++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (result.contentPresent || result.source) {\n\t\t\treturn generationConflictResult({ refreshedSourceCount: 0, deletedSourceCount });\n\t\t}\n\t}\n\treturn { ...ZERO_RESULT, deletedSourceCount };\n}\n\nexport async function markContentMediaUsageCollectionStaleSafely(\n\tdb: Kysely<Database>,\n\tcollectionSlug: string,\n\tlastErrorCode: ContentMediaUsageRefreshErrorCode,\n): Promise<boolean> {\n\ttry {\n\t\tawait markContentMediaUsageCollectionStale(db, collectionSlug, lastErrorCode);\n\t\treturn true;\n\t} catch (error) {\n\t\tconsole.error(`[media-usage] Failed to mark ${collectionSlug} stale:`, error);\n\t\treturn false;\n\t}\n}\n\nasync function withContentUsageLock<T>(\n\tcollectionSlug: string,\n\tcontentId: string,\n\tfn: () => Promise<T>,\n): Promise<T> {\n\tconst locks = getContentUsageLocks();\n\tconst lockKey = `${collectionSlug}\\0${contentId}`;\n\tconst previous = locks.get(lockKey) ?? Promise.resolve();\n\tlet releaseCurrent!: () => void;\n\tconst current = new Promise<void>((resolve) => {\n\t\treleaseCurrent = resolve;\n\t});\n\tconst next = previous.catch(() => {}).then(() => current);\n\tlocks.set(lockKey, next);\n\n\ttry {\n\t\tawait previous.catch(() => {});\n\t\treturn await fn();\n\t} finally {\n\t\treleaseCurrent();\n\t\tif (locks.get(lockKey) === next) locks.delete(lockKey);\n\t}\n}\n\nexport async function withContentUsageCollectionLock<T>(\n\tcollectionSlug: string,\n\tfn: () => Promise<T>,\n): Promise<T> {\n\t// Coarse by design: row refreshes and collection source deletes must not interleave.\n\tconst locks = getContentUsageCollectionLocks();\n\tconst previous = locks.get(collectionSlug) ?? Promise.resolve();\n\tlet releaseCurrent!: () => void;\n\tconst current = new Promise<void>((resolve) => {\n\t\treleaseCurrent = resolve;\n\t});\n\tconst next = previous.catch(() => {}).then(() => current);\n\tlocks.set(collectionSlug, next);\n\n\ttry {\n\t\tawait previous.catch(() => {});\n\t\treturn await fn();\n\t} finally {\n\t\treleaseCurrent();\n\t\tif (locks.get(collectionSlug) === next) locks.delete(collectionSlug);\n\t}\n}\n\nfunction getContentUsageLocks(): Map<string, Promise<void>> {\n\tconst global = globalThis as typeof globalThis & Record<symbol, unknown>;\n\tconst existing = global[CONTENT_USAGE_LOCKS_KEY];\n\t// eslint-disable-next-line typescript/no-unsafe-type-assertion -- globalThis symbol slot stores only this map\n\tif (existing instanceof Map) return existing as Map<string, Promise<void>>;\n\tconst locks = new Map<string, Promise<void>>();\n\tglobal[CONTENT_USAGE_LOCKS_KEY] = locks;\n\treturn locks;\n}\n\nfunction getContentUsageCollectionLocks(): Map<string, Promise<void>> {\n\tconst global = globalThis as typeof globalThis & Record<symbol, unknown>;\n\tconst existing = global[CONTENT_USAGE_COLLECTION_LOCKS_KEY];\n\t// eslint-disable-next-line typescript/no-unsafe-type-assertion -- globalThis symbol slot stores only this map\n\tif (existing instanceof Map) return existing as Map<string, Promise<void>>;\n\tconst locks = new Map<string, Promise<void>>();\n\tglobal[CONTENT_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