{"version":3,"file":"loader-C3bws5Wb.mjs","names":[],"sources":["../src/loader.ts"],"sourcesContent":["/**\n * Astro Live Collections loader for EmDash\n *\n * This loader implements the Astro LiveLoader interface to fetch content\n * at runtime from the database, enabling live editing without rebuilds.\n *\n * Architecture:\n * - Single `_emdash` Astro collection handles all content types\n * - Dialect comes from virtual module (configured in astro.config.mjs)\n * - Each content type maps to its own database table: ec_posts, ec_products, etc.\n * - `getEmDashCollection()` / `getEmDashEntry()` wrap Astro's live collection API\n */\n\nimport type { LiveLoader } from \"astro/loaders\";\nimport { Kysely, type RawBuilder, sql, type Dialect } from \"kysely\";\n\nimport { buildStatusCondition, isPostgres } from \"./database/dialect-helpers.js\";\nimport { kyselyLogOption } from \"./database/instrumentation.js\";\nimport { decodeCursor, encodeCursor } from \"./database/repositories/types.js\";\nimport { validateIdentifier } from \"./database/validate.js\";\nimport { getI18nConfig } from \"./i18n/config.js\";\nimport type { Database } from \"./index.js\";\nimport { getRequestContext } from \"./request-context.js\";\nimport { isMissingColumnError, isMissingTableError } from \"./utils/db-errors.js\";\n\nconst FIELD_NAME_PATTERN = /^[a-zA-Z_][a-zA-Z0-9_]*$/;\n\n/**\n * SEO columns folded into the single-entry query as a single JSON column\n * (`_emdash_seo` in the result set), then expanded onto the row under these\n * aliases for `extractSeo()`. Surfacing SEO as one aggregated column keeps the\n * result-set width bounded regardless of how many fields the collection has,\n * which matters for D1: a flat `LEFT JOIN _emdash_seo` adds 5 alias columns to\n * every row and pushes wide collections (common after WordPress / ACF imports)\n * past D1's per-result-set column limit, surfacing as a silent null entry.\n * One JSON column is one column, so the join stays safe at any schema width.\n *\n * The aliases mirror the strategy used by `foldedHydrationSelects` for byline\n * and taxonomy hydration: aggregate in SQL, expand in JS. SEO is 1:1 with\n * content, so the subquery uses `json_object` (not the array aggregator).\n *\n * The `_emdash_` prefix on the aliases guarantees they can never collide with\n * a content field. Field slugs must match `/^[a-z][a-z0-9_]*$/`, so a user can\n * legitimately define a `seo_title` field; surfacing the SEO column under its\n * bare name would shadow that field in the result set and drop the user's\n * value. The prefix (illegal as a leading slug char) sidesteps this entirely.\n */\nconst SEO_COLUMN_ALIASES: Record<string, string> = {\n\tseo_title: \"_emdash_seo_title\",\n\tseo_description: \"_emdash_seo_description\",\n\tseo_image: \"_emdash_seo_image\",\n\tseo_canonical: \"_emdash_seo_canonical\",\n\tseo_no_index: \"_emdash_seo_no_index\",\n};\n\n/** Aliased SEO result keys — excluded from generic field mapping. */\nconst SEO_ALIAS_COLUMNS = Object.values(SEO_COLUMN_ALIASES);\n\n/** Folded SEO JSON column name in the result set (expanded onto aliases in JS). */\nconst SEO_FOLDED_COLUMN = \"_emdash_seo\";\n\n/**\n * System columns excluded from entry.data\n * Note: slug is intentionally NOT excluded - it's useful as data.slug in templates\n */\nconst SYSTEM_COLUMNS = new Set([\n\t\"id\",\n\t// \"slug\" - kept in data for template access\n\t\"status\",\n\t\"author_id\",\n\t\"primary_byline_id\",\n\t\"created_at\",\n\t\"updated_at\",\n\t\"published_at\",\n\t\"scheduled_at\",\n\t\"deleted_at\",\n\t\"version\",\n\t\"live_revision_id\",\n\t\"draft_revision_id\",\n\t\"locale\",\n\t\"translation_group\",\n\t// Aliased SEO columns expanded from the folded _emdash_seo JSON column on\n\t// the single-entry path. Surfaced as a nested data.seo object (see\n\t// extractSeo), never as flat fields. The aliases are _emdash_-prefixed so\n\t// they can't shadow a user field named e.g. `seo_title`.\n\t...SEO_ALIAS_COLUMNS,\n\t// Folded hydration JSON columns (see foldedHydrationSelects and\n\t// foldedSeoSelect) — surfaced via the FOLDED_* markers or expanded onto\n\t// SEO_ALIAS_COLUMNS, never as flat fields.\n\t\"_emdash_terms\",\n\t\"_emdash_bylines\",\n\t\"_emdash_bylines_exist\",\n\tSEO_FOLDED_COLUMN,\n]);\n\n/** Markers for byline/taxonomy hydration folded into the content query. */\nexport const FOLDED_TERMS = Symbol.for(\"emdash:foldedTerms\");\nexport const FOLDED_BYLINES = Symbol.for(\"emdash:foldedBylines\");\n/**\n * Marker for whether `_emdash_bylines` has any rows at all (`false` = table\n * empty). Lets byline hydration trust an empty fold instead of re-checking\n * via the byline query path on sites that never use bylines.\n */\nexport const FOLDED_BYLINES_EXIST = Symbol.for(\"emdash:foldedBylinesExist\");\n\n/**\n * Correlated JSON-array subqueries that fold taxonomy-term and byline hydration\n * into the content query, removing the two separate hydration round trips per\n * fetch. `outer` is the content table's alias/name; each subquery correlates on\n * `<outer>.id`, so the base query stays one row per entry (no join fan-out, no\n * duplicated content payload). Order is NOT applied in the aggregate (it differs\n * across dialects) — the consumer sorts terms by label and credits by sortOrder.\n *\n * Dialect-specific aggregation: SQLite `json_group_array`/`json_object` returns\n * a JSON *string*; Postgres `json_agg`/`json_build_object` (coalesced to `[]`)\n * returns parsed JSON. {@link stashFolded} handles both.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- any Kysely instance\nfunction foldedHydrationSelects(db: Kysely<any>, type: string, outer: string) {\n\tconst o = sql.ref(outer);\n\tconst pg = isPostgres(db);\n\tconst obj = (pairs: string) =>\n\t\tpg ? sql.raw(`json_build_object(${pairs})`) : sql.raw(`json_object(${pairs})`);\n\tconst agg = (inner: RawBuilder<unknown>) =>\n\t\tpg ? sql`coalesce(json_agg(${inner}), '[]'::json)` : sql`json_group_array(${inner})`;\n\n\t// Pin the byline join order on SQLite (#1722). Taxonomy hydration uses\n\t// LEFT JOINs below, whose order is already fixed by SQL semantics. SQLite\n\t// honours `CROSS JOIN` ordering, forcing the byline subquery to drive from\n\t// its pivot by content reference and probe by translation_group. Postgres\n\t// keeps statistics and rejects `CROSS JOIN … ON`, so it stays a plain JOIN.\n\tconst foldJoin = pg ? sql`JOIN` : sql`CROSS JOIN`;\n\n\tconst termObj = obj(\n\t\t\"'id', coalesce(exact_term.id, default_term.id), 'name', coalesce(exact_term.name, default_term.name), 'slug', coalesce(exact_term.slug, default_term.slug), 'label', coalesce(exact_term.label, default_term.label), 'parent_id', coalesce(exact_term.parent_id, default_term.parent_id), 'locale', coalesce(exact_term.locale, default_term.locale), 'translation_group', coalesce(exact_term.translation_group, default_term.translation_group)\",\n\t);\n\tconst defaultLocale = getI18nConfig()?.defaultLocale ?? \"en\";\n\tconst selectedTermId = sql`coalesce(exact_term.id, default_term.id)`;\n\tconst termAgg = pg\n\t\t? sql`coalesce(json_agg(${termObj}) FILTER (WHERE ${selectedTermId} IS NOT NULL), '[]'::json)`\n\t\t: sql`json_group_array(${termObj}) FILTER (WHERE ${selectedTermId} IS NOT NULL)`;\n\tconst terms = sql`(SELECT ${termAgg} FROM ${sql.ref(\"content_taxonomies\")} AS ct LEFT JOIN ${sql.ref(\"taxonomies\")} AS exact_term ON exact_term.translation_group = ct.taxonomy_id AND exact_term.locale = ${o}.locale LEFT JOIN ${sql.ref(\"taxonomies\")} AS default_term ON default_term.translation_group = ct.taxonomy_id AND default_term.locale = ${defaultLocale} WHERE ct.collection = ${type} AND ct.entry_id = ${o}.translation_group) AS ${sql.ref(\"_emdash_terms\")}`;\n\n\tconst bylineInner = obj(\n\t\t\"'id', b.id, 'slug', b.slug, 'displayName', b.display_name, 'bio', b.bio, 'avatarMediaId', b.avatar_media_id, 'avatarStorageKey', m.storage_key, 'avatarAlt', m.alt, 'avatarBlurhash', m.blurhash, 'avatarDominantColor', m.dominant_color, 'websiteUrl', b.website_url, 'userId', b.user_id, 'isGuest', b.is_guest, 'createdAt', b.created_at, 'updatedAt', b.updated_at, 'locale', b.locale, 'translationGroup', b.translation_group\",\n\t);\n\tconst creditObj = pg\n\t\t? sql.raw(\n\t\t\t\t\"json_build_object('roleLabel', cb.role_label, 'sortOrder', cb.sort_order, 'byline', \",\n\t\t\t)\n\t\t: sql.raw(\"json_object('roleLabel', cb.role_label, 'sortOrder', cb.sort_order, 'byline', \");\n\tconst credit = sql`${creditObj}${bylineInner})`;\n\tconst bylines = sql`(SELECT ${agg(credit)} FROM ${sql.ref(\"_emdash_content_bylines\")} AS cb ${foldJoin} ${sql.ref(\"_emdash_bylines\")} AS b ON b.translation_group = cb.byline_id LEFT JOIN ${sql.ref(\"media\")} AS m ON m.id = b.avatar_media_id WHERE cb.collection_slug = ${type} AND cb.content_id = ${o}.id AND b.locale = ${o}.locale) AS ${sql.ref(\"_emdash_bylines\")}`;\n\t// Uncorrelated existence probe (evaluated once per statement, not per row):\n\t// 1 when `_emdash_bylines` has any row, NULL when empty. An empty table\n\t// means an empty fold is authoritative — no credit in any locale, no\n\t// author-fallback byline — so hydration can skip the byline query path.\n\tconst bylinesExist = sql`(SELECT 1 FROM ${sql.ref(\"_emdash_bylines\")} LIMIT 1) AS ${sql.ref(\"_emdash_bylines_exist\")}`;\n\treturn { terms, bylines, bylinesExist };\n}\n\n/**\n * Correlated JSON-object subquery that folds per-entry SEO into the content\n * query without widening the result set: 1 row of `_emdash_seo` becomes 1 JSON\n * column rather than 5 flat columns. The JSON column is expanded onto the row\n * via {@link expandFoldedSeo} after the query runs, preserving the alias keys\n * that {@link extractSeo} reads. Missing SEO row (no entry in `_emdash_seo`)\n * yields NULL, which {@link expandFoldedSeo} treats as \"no SEO\" - identical to\n * the prior LEFT JOIN miss behavior.\n *\n * Dialect-specific aggregation mirrors {@link foldedHydrationSelects}: SQLite\n * `json_object` returns a JSON *string*, Postgres `json_build_object` returns\n * parsed JSON; both branches are handled in expansion.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- any Kysely instance\nfunction foldedSeoSelect(db: Kysely<any>, type: string, outer: string) {\n\tconst o = sql.ref(outer);\n\tconst pg = isPostgres(db);\n\t// Use raw column names (not aliases) as JSON keys: the JSON is expanded back\n\t// onto SEO_COLUMN_ALIASES in JS, and keeping the keys matched to the\n\t// underlying columns makes the SQL readable and the expansion 1-to-1.\n\tconst pairs =\n\t\t\"'seo_title', s.seo_title, 'seo_description', s.seo_description, 'seo_image', s.seo_image, 'seo_canonical', s.seo_canonical, 'seo_no_index', s.seo_no_index\";\n\tconst obj = pg ? sql.raw(`json_build_object(${pairs})`) : sql.raw(`json_object(${pairs})`);\n\treturn sql`(SELECT ${obj} FROM ${sql.ref(\"_emdash_seo\")} AS s WHERE s.collection = ${type} AND s.content_id = ${o}.id LIMIT 1) AS ${sql.ref(SEO_FOLDED_COLUMN)}`;\n}\n\n/**\n * Expand the folded `_emdash_seo` JSON column onto the row using SEO_COLUMN_ALIASES,\n * so {@link extractSeo} reads it transparently. SQLite returns a JSON string\n * (parse it); Postgres returns already-parsed JSON. Missing/malformed/null is\n * a no-op: {@link extractSeo} returns null when the aliases are absent.\n */\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n\treturn !!value && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction expandFoldedSeo(row: Record<string, unknown>): void {\n\tconst raw = row[SEO_FOLDED_COLUMN];\n\tdelete row[SEO_FOLDED_COLUMN];\n\tlet parsed: Record<string, unknown> | null = null;\n\tif (typeof raw === \"string\") {\n\t\ttry {\n\t\t\tconst candidate: unknown = JSON.parse(raw);\n\t\t\tif (isPlainObject(candidate)) parsed = candidate;\n\t\t} catch {\n\t\t\treturn; // malformed JSON: leave the row without SEO aliases (extractSeo returns null)\n\t\t}\n\t} else if (isPlainObject(raw)) {\n\t\tparsed = raw;\n\t}\n\tif (!parsed) return;\n\tfor (const [col, alias] of Object.entries(SEO_COLUMN_ALIASES)) {\n\t\trow[alias] = parsed[col] ?? null;\n\t}\n}\n\nexport function creditsFromFoldedBylines(folded: unknown[]) {\n\treturn folded\n\t\t.map((raw) => {\n\t\t\tconst credit = isPlainObject(raw) ? raw : {};\n\t\t\tconst byline = isPlainObject(credit.byline) ? credit.byline : {};\n\t\t\treturn {\n\t\t\t\troleLabel: typeof credit.roleLabel === \"string\" ? credit.roleLabel : null,\n\t\t\t\tsortOrder: Number(credit.sortOrder ?? 0),\n\t\t\t\tsource: \"explicit\" as const,\n\t\t\t\tbyline: {\n\t\t\t\t\t...byline,\n\t\t\t\t\tisGuest: Boolean(byline.isGuest),\n\t\t\t\t\t// Folded rows omit custom-field values.\n\t\t\t\t\tcustomFields: {},\n\t\t\t\t},\n\t\t\t};\n\t\t})\n\t\t.toSorted((a, b) => a.sortOrder - b.sortOrder);\n}\n\n/**\n * Stash folded hydration JSON (non-enumerable) for the query.ts fast paths.\n * SQLite returns a JSON string (parse it); Postgres returns already-parsed JSON.\n */\nfunction stashFolded(data: Record<string, unknown>, row: Record<string, unknown>): void {\n\tfor (const [col, sym] of [\n\t\t[\"_emdash_terms\", FOLDED_TERMS],\n\t\t[\"_emdash_bylines\", FOLDED_BYLINES],\n\t] as const) {\n\t\tconst raw = row[col];\n\t\tlet value: unknown;\n\t\tif (typeof raw === \"string\") {\n\t\t\ttry {\n\t\t\t\tvalue = JSON.parse(raw);\n\t\t\t} catch {\n\t\t\t\tcontinue; // malformed: fall back to the query path\n\t\t\t}\n\t\t} else if (Array.isArray(raw)) {\n\t\t\tvalue = raw; // Postgres json/jsonb already parsed by the driver\n\t\t} else {\n\t\t\tcontinue;\n\t\t}\n\t\tObject.defineProperty(data, sym, { value, enumerable: false, configurable: true });\n\t}\n\t// Existence probe: 1 = table has rows, NULL = empty (both dialects). A row\n\t// without the column (e.g. a cached snapshot) leaves the marker unset,\n\t// which hydration treats as \"unknown\" and falls back conservatively.\n\tif (\"_emdash_bylines_exist\" in row) {\n\t\tObject.defineProperty(data, FOLDED_BYLINES_EXIST, {\n\t\t\tvalue: row[\"_emdash_bylines_exist\"] != null,\n\t\t\tenumerable: false,\n\t\t\tconfigurable: true,\n\t\t});\n\t}\n\n\tconst foldedBylines = Reflect.get(data, FOLDED_BYLINES);\n\tif (!Array.isArray(foldedBylines)) return;\n\tconst credits = creditsFromFoldedBylines(foldedBylines);\n\tdata.bylines = credits;\n\tdata.byline = credits[0]?.byline ?? null;\n}\n\n/** Resolved SEO shape attached to `entry.data.seo`. Mirrors `ContentSeo`. */\ninterface EntrySeo {\n\ttitle: string | null;\n\tdescription: string | null;\n\timage: string | null;\n\tcanonical: string | null;\n\tnoIndex: boolean;\n}\n\n/**\n * Build a `data.seo` object from the joined `_emdash_seo` columns on a row.\n *\n * Returns `null` when no SEO row exists (LEFT JOIN miss → `seo_no_index` is\n * NULL, since the column is `NOT NULL DEFAULT 0` whenever a row is present).\n * Returning null keeps the `seo` key off entries that have none, so\n * `getSeoMeta()` falls back to its defaults exactly as before.\n */\nfunction extractSeo(row: Record<string, unknown>): EntrySeo | null {\n\tconst noIndex = row[SEO_COLUMN_ALIASES.seo_no_index];\n\tif (noIndex === null || noIndex === undefined) return null;\n\tconst title = row[SEO_COLUMN_ALIASES.seo_title];\n\tconst description = row[SEO_COLUMN_ALIASES.seo_description];\n\tconst image = row[SEO_COLUMN_ALIASES.seo_image];\n\tconst canonical = row[SEO_COLUMN_ALIASES.seo_canonical];\n\treturn {\n\t\ttitle: typeof title === \"string\" ? title : null,\n\t\tdescription: typeof description === \"string\" ? description : null,\n\t\timage: typeof image === \"string\" ? image : null,\n\t\tcanonical: typeof canonical === \"string\" ? canonical : null,\n\t\tnoIndex: noIndex === 1,\n\t};\n}\n\n/**\n * Get the table name for a collection type\n */\nfunction getTableName(type: string): string {\n\tvalidateIdentifier(type, \"collection type\");\n\treturn `ec_${type}`;\n}\n\n/**\n * Cache for taxonomy names by collection (only used for the primary database).\n * Stored on globalThis so Vite SSR chunk duplication cannot create independent\n * caches. Skipped when a per-request DB override is active (e.g. preview mode)\n * because the override DB may have different taxonomies.\n */\ninterface TaxonomyNamesHolder {\n\tcache: Map<string, Set<string>> | null;\n}\n\nconst TAXONOMY_NAMES_CACHE_KEY = Symbol.for(\"emdash:taxonomy-names\");\nconst taxonomyNamesStore = globalThis as Record<symbol, unknown>;\nconst taxonomyNamesHolder: TaxonomyNamesHolder =\n\t// eslint-disable-next-line typescript/no-unsafe-type-assertion -- globalThis singleton pattern (see taxonomies/index.ts)\n\t(taxonomyNamesStore[TAXONOMY_NAMES_CACHE_KEY] as TaxonomyNamesHolder | undefined) ??\n\t(() => {\n\t\tconst holder: TaxonomyNamesHolder = { cache: null };\n\t\ttaxonomyNamesStore[TAXONOMY_NAMES_CACHE_KEY] = holder;\n\t\treturn holder;\n\t})();\n\nfunction setTaxonomyNamesCache(cache: Map<string, Set<string>> | null): void {\n\ttaxonomyNamesHolder.cache = cache;\n}\n\n/**\n * Get taxonomy names attached to a collection (cached for the primary DB,\n * bypassed only when the per-request DB is an isolated instance — playground /\n * DO preview). Plain D1 Sessions routing shares schema with the singleton, so\n * the isolate-wide cache stays valid.\n */\nasync function getTaxonomyNames(db: Kysely<Database>, collection: string): Promise<Set<string>> {\n\tconst hasIsolatedDb = getRequestContext()?.dbIsIsolated === true;\n\n\tif (!hasIsolatedDb && taxonomyNamesHolder.cache) {\n\t\treturn taxonomyNamesHolder.cache.get(collection) ?? new Set();\n\t}\n\n\ttry {\n\t\tconst defs = await db\n\t\t\t.selectFrom(\"_emdash_taxonomy_defs\")\n\t\t\t.select([\"name\", \"collections\"])\n\t\t\t.execute();\n\t\tconst namesByCollection = new Map<string, Set<string>>();\n\t\tfor (const def of defs) {\n\t\t\tlet collections: unknown;\n\t\t\ttry {\n\t\t\t\tcollections = JSON.parse(def.collections ?? \"[]\");\n\t\t\t} catch {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!Array.isArray(collections)) continue;\n\t\t\tfor (const attachedCollection of collections) {\n\t\t\t\tif (typeof attachedCollection !== \"string\") continue;\n\t\t\t\tconst names = namesByCollection.get(attachedCollection) ?? new Set<string>();\n\t\t\t\tnames.add(def.name);\n\t\t\t\tnamesByCollection.set(attachedCollection, names);\n\t\t\t}\n\t\t}\n\t\tif (!hasIsolatedDb) {\n\t\t\tsetTaxonomyNamesCache(namesByCollection);\n\t\t}\n\t\treturn namesByCollection.get(collection) ?? new Set();\n\t} catch (error) {\n\t\tif (!isMissingTableError(error) && !isMissingColumnError(error)) throw error;\n\n\t\tconst empty = new Set<string>();\n\t\tif (!hasIsolatedDb) {\n\t\t\tsetTaxonomyNamesCache(new Map());\n\t\t}\n\t\treturn empty;\n\t}\n}\n\n/**\n * Reset the isolate-wide taxonomy-names cache.\n *\n * Called from `invalidateTaxonomyDefsCache()` so that creating or seeding a\n * taxonomy definition is reflected within the current isolate instead of\n * waiting for the isolate to recycle. Keeps this cache consistent with the\n * isolate-wide taxonomy-defs cache in `taxonomies/index.ts`.\n */\nexport function resetTaxonomyNamesCache(): void {\n\tsetTaxonomyNamesCache(null);\n}\n\n/**\n * System columns to include in data (mapped to camelCase where needed)\n */\nconst INCLUDE_IN_DATA: Record<string, string> = {\n\tid: \"id\",\n\tstatus: \"status\",\n\tauthor_id: \"authorId\",\n\tprimary_byline_id: \"primaryBylineId\",\n\tcreated_at: \"createdAt\",\n\tupdated_at: \"updatedAt\",\n\tpublished_at: \"publishedAt\",\n\tscheduled_at: \"scheduledAt\",\n\tdraft_revision_id: \"draftRevisionId\",\n\tlive_revision_id: \"liveRevisionId\",\n\tlocale: \"locale\",\n\ttranslation_group: \"translationGroup\",\n};\n\n/** System date columns that should be converted to Date objects */\nconst DATE_COLUMNS = new Set([\"created_at\", \"updated_at\", \"published_at\", \"scheduled_at\"]);\n\n/**\n * Hidden, symbol-keyed property on each mapped data record carrying the raw\n * DB string for every date column. Lets cursor encoders downstream reproduce\n * the loader's exact `nextCursor` format without round-tripping through\n * `new Date()`, which loses precision for stored values that aren't already\n * ISO-with-milliseconds (e.g. `2026-01-01T00:00:00Z` becomes\n * `2026-01-01T00:00:00.000Z`).\n */\nexport const CURSOR_RAW_VALUES: unique symbol = Symbol(\"emdash:cursorRawValues\");\n\nconst LOCAL_MEDIA_FILE_PREFIX = \"/_emdash/api/media/file/\";\nconst URL_SCHEME_PATTERN = /^[a-zA-Z][a-zA-Z\\d+\\-.]*:/;\n\n/** Safely extract a string value from a record, returning fallback if not a string */\nfunction rowStr(row: Record<string, unknown>, key: string, fallback = \"\"): string {\n\tconst val = row[key];\n\treturn typeof val === \"string\" ? val : fallback;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isBareMediaKey(src: string): boolean {\n\treturn !src.startsWith(\"/\") && !URL_SCHEME_PATTERN.test(src);\n}\n\nfunction normalizeLocalMediaValue(value: unknown): unknown {\n\tif (Array.isArray(value)) {\n\t\treturn value.map(normalizeLocalMediaValue);\n\t}\n\n\tif (!isRecord(value)) {\n\t\treturn value;\n\t}\n\n\tconst normalized: Record<string, unknown> = {};\n\tfor (const [key, child] of Object.entries(value)) {\n\t\tnormalized[key] = normalizeLocalMediaValue(child);\n\t}\n\n\tif (\n\t\tnormalized.provider === \"local\" &&\n\t\ttypeof normalized.src === \"string\" &&\n\t\tnormalized.src.length > 0\n\t) {\n\t\tconst src = normalized.src;\n\t\tif (src.startsWith(LOCAL_MEDIA_FILE_PREFIX)) {\n\t\t\tconst id = src.slice(LOCAL_MEDIA_FILE_PREFIX.length);\n\t\t\tif (!normalized.id && id) {\n\t\t\t\tnormalized.id = id;\n\t\t\t}\n\t\t} else if (isBareMediaKey(src)) {\n\t\t\tif (!normalized.id) {\n\t\t\t\tnormalized.id = src;\n\t\t\t}\n\t\t\tnormalized.src = `${LOCAL_MEDIA_FILE_PREFIX}${src}`;\n\t\t}\n\t}\n\n\treturn normalized;\n}\n\n/**\n * Map a database row to entry data\n * Extracts content fields (non-system columns) and parses JSON where needed.\n * System columns needed for templates (id, status, dates) are included with camelCase names.\n */\nfunction mapRowToData(row: Record<string, unknown>): Record<string, unknown> {\n\tconst data: Record<string, unknown> = {};\n\tconst rawDateValues: Record<string, string> = {};\n\n\tfor (const [key, value] of Object.entries(row)) {\n\t\t// Include certain system columns (mapped to camelCase where needed)\n\t\tif (key in INCLUDE_IN_DATA) {\n\t\t\t// Convert date columns from ISO strings to Date objects\n\t\t\tif (DATE_COLUMNS.has(key)) {\n\t\t\t\tif (typeof value === \"string\") {\n\t\t\t\t\trawDateValues[key] = value;\n\t\t\t\t\tdata[INCLUDE_IN_DATA[key]] = new Date(value);\n\t\t\t\t} else {\n\t\t\t\t\tdata[INCLUDE_IN_DATA[key]] = null;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tdata[INCLUDE_IN_DATA[key]] = value;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (SYSTEM_COLUMNS.has(key)) continue;\n\n\t\t// Try to parse JSON strings (for portableText, json fields, etc.)\n\t\tif (typeof value === \"string\") {\n\t\t\ttry {\n\t\t\t\t// Only parse if it looks like JSON (starts with { or [)\n\t\t\t\tif (value.startsWith(\"{\") || value.startsWith(\"[\")) {\n\t\t\t\t\tdata[key] = normalizeLocalMediaValue(JSON.parse(value));\n\t\t\t\t} else {\n\t\t\t\t\tdata[key] = value;\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\tdata[key] = value;\n\t\t\t}\n\t\t} else {\n\t\t\tdata[key] = value;\n\t\t}\n\t}\n\n\tObject.defineProperty(data, CURSOR_RAW_VALUES, {\n\t\tvalue: rawDateValues,\n\t\tenumerable: false,\n\t\tconfigurable: false,\n\t\twritable: false,\n\t});\n\n\treturn data;\n}\n\n/**\n * Map revision data (already-parsed JSON object) to entry data.\n * Strips _-prefixed metadata keys (e.g. _slug) used internally by revisions.\n */\nfunction mapRevisionData(data: Record<string, unknown>): Record<string, unknown> {\n\tconst result: Record<string, unknown> = {};\n\tfor (const [key, value] of Object.entries(data)) {\n\t\tif (key.startsWith(\"_\")) continue; // revision metadata\n\t\tresult[key] = normalizeLocalMediaValue(value);\n\t}\n\treturn result;\n}\n\n// Virtual module imports are lazy-loaded to avoid errors when importing\n// emdash outside of Astro/Vite context (e.g., in astro.config.mjs)\nlet virtualConfig:\n\t| {\n\t\t\tdatabase?: { config: unknown };\n\t\t\ti18n?: { defaultLocale: string; locales: string[]; prefixDefaultLocale?: boolean } | null;\n\t  }\n\t| undefined;\nlet virtualCreateDialect: ((config: unknown) => Dialect) | undefined;\n\nasync function loadVirtualModules() {\n\tif (virtualConfig === undefined) {\n\t\t// eslint-disable-next-line @typescript-eslint/ban-ts-comment\n\t\t// @ts-ignore - virtual module\n\t\tconst configModule = await import(\"virtual:emdash/config\");\n\t\tvirtualConfig = configModule.default;\n\t}\n\tif (virtualCreateDialect === undefined) {\n\t\t// eslint-disable-next-line @typescript-eslint/ban-ts-comment\n\t\t// @ts-ignore - virtual module\n\t\tconst dialectModule = await import(\"virtual:emdash/dialect\");\n\t\tvirtualCreateDialect = dialectModule.createDialect;\n\t\t// dialectType is no longer needed here — dialect detection is\n\t\t// done via the db adapter instance in dialect-helpers.ts\n\t}\n}\n\n/**\n * Entry data type - generic object\n */\nexport type EntryData = Record<string, unknown>;\n\n/**\n * Sort direction\n */\nexport type SortDirection = \"asc\" | \"desc\";\n\n/**\n * Order by specification - field name to direction\n * @example { created_at: \"desc\" } - Sort by created_at descending\n * @example { title: \"asc\" } - Sort by title ascending\n */\nexport type OrderBySpec = Record<string, SortDirection>;\n\n/**\n * Resolved primary sort field and direction (used for cursor pagination).\n */\ninterface PrimarySort {\n\tfield: string;\n\tdirection: SortDirection;\n}\n\n/**\n * Get the primary sort field from an orderBy spec (first valid field, or default).\n */\nfunction getPrimarySort(orderBy: OrderBySpec | undefined, tablePrefix?: string): PrimarySort {\n\tif (orderBy) {\n\t\tfor (const [field, direction] of Object.entries(orderBy)) {\n\t\t\tif (FIELD_NAME_PATTERN.test(field)) {\n\t\t\t\tconst fullField = tablePrefix ? `${tablePrefix}.${field}` : field;\n\t\t\t\treturn { field: fullField, direction };\n\t\t\t}\n\t\t}\n\t}\n\tconst defaultField = tablePrefix ? `${tablePrefix}.created_at` : \"created_at\";\n\treturn { field: defaultField, direction: \"desc\" };\n}\n\n/**\n * Build ORDER BY clause from orderBy spec\n * Validates field names to prevent SQL injection (alphanumeric + underscore only)\n * Supports multiple sort fields in object key order\n */\nfunction buildOrderByClause(\n\torderBy: OrderBySpec | undefined,\n\ttablePrefix?: string,\n): ReturnType<typeof sql> {\n\t// Default to created_at DESC\n\tif (!orderBy || Object.keys(orderBy).length === 0) {\n\t\tconst field = tablePrefix ? `${tablePrefix}.created_at` : \"created_at\";\n\t\treturn sql`ORDER BY ${sql.ref(field)} DESC, ${sql.ref(tablePrefix ? `${tablePrefix}.id` : \"id\")} DESC`;\n\t}\n\n\tconst sortParts: ReturnType<typeof sql>[] = [];\n\n\tfor (const [field, direction] of Object.entries(orderBy)) {\n\t\t// Validate field name (alphanumeric + underscore only)\n\t\tif (!FIELD_NAME_PATTERN.test(field)) {\n\t\t\tcontinue; // Skip invalid field names\n\t\t}\n\n\t\tconst fullField = tablePrefix ? `${tablePrefix}.${field}` : field;\n\t\tconst dir = direction === \"asc\" ? sql`ASC` : sql`DESC`;\n\t\tsortParts.push(sql`${sql.ref(fullField)} ${dir}`);\n\t}\n\n\t// If no valid sort fields, fall back to default\n\tif (sortParts.length === 0) {\n\t\tconst defaultField = tablePrefix ? `${tablePrefix}.created_at` : \"created_at\";\n\t\treturn sql`ORDER BY ${sql.ref(defaultField)} DESC, ${sql.ref(tablePrefix ? `${tablePrefix}.id` : \"id\")} DESC`;\n\t}\n\n\t// Add id as tiebreaker to ensure stable cursor ordering\n\tconst primary = getPrimarySort(orderBy, tablePrefix);\n\tconst idField = tablePrefix ? `${tablePrefix}.id` : \"id\";\n\tconst idDir = primary.direction === \"asc\" ? sql`ASC` : sql`DESC`;\n\tsortParts.push(sql`${sql.ref(idField)} ${idDir}`);\n\n\treturn sql`ORDER BY ${sql.join(sortParts, sql`, `)}`;\n}\n\n/**\n * Build a cursor WHERE condition for keyset pagination.\n * Uses the primary sort field + id as tiebreaker for stable ordering.\n *\n * Throws `InvalidCursorError` if the cursor is malformed; callers should\n * let this propagate so users see a real error rather than silently\n * falling back to the first page.\n */\nfunction buildCursorCondition(\n\tcursor: string,\n\torderBy: OrderBySpec | undefined,\n\ttablePrefix?: string,\n): ReturnType<typeof sql> {\n\tconst { orderValue, id: cursorId } = decodeCursor(cursor);\n\tconst primary = getPrimarySort(orderBy, tablePrefix);\n\tconst idField = tablePrefix ? `${tablePrefix}.id` : \"id\";\n\n\tif (primary.direction === \"desc\") {\n\t\treturn sql`(${sql.ref(primary.field)} < ${orderValue} OR (${sql.ref(primary.field)} = ${orderValue} AND ${sql.ref(idField)} < ${cursorId}))`;\n\t}\n\treturn sql`(${sql.ref(primary.field)} > ${orderValue} OR (${sql.ref(primary.field)} = ${orderValue} AND ${sql.ref(idField)} > ${cursorId}))`;\n}\n\n/** Type guard: is the where value a range object (not a string or array)? */\nfunction isWhereRange(value: WhereValue): value is WhereRange {\n\treturn value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\n/**\n * Build AND conditions for non-taxonomy field filters.\n * Returns an array of sql fragments; empty if no field filters apply.\n * Field names are validated against FIELD_NAME_PATTERN to prevent injection.\n */\nfunction buildFieldConditions(\n\tfields: Record<string, WhereValue>,\n\ttablePrefix?: string,\n): ReturnType<typeof sql>[] {\n\tconst conditions: ReturnType<typeof sql>[] = [];\n\n\tfor (const [key, value] of Object.entries(fields)) {\n\t\tif (!FIELD_NAME_PATTERN.test(key)) {\n\t\t\tconsole.warn(`[emdash] where filter: invalid field name \"${key}\" ignored`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (value == null) continue;\n\t\tconst ref = tablePrefix ? sql.ref(`${tablePrefix}.${key}`) : sql.ref(key);\n\n\t\tif (isWhereRange(value)) {\n\t\t\tif (value.gt !== undefined) conditions.push(sql`${ref} > ${value.gt}`);\n\t\t\tif (value.gte !== undefined) conditions.push(sql`${ref} >= ${value.gte}`);\n\t\t\tif (value.lt !== undefined) conditions.push(sql`${ref} < ${value.lt}`);\n\t\t\tif (value.lte !== undefined) conditions.push(sql`${ref} <= ${value.lte}`);\n\t\t} else if (Array.isArray(value)) {\n\t\t\tif (value.length > 0) {\n\t\t\t\tconditions.push(sql`${ref} IN (${sql.join(value.map((v) => sql`${v}`))})`);\n\t\t\t}\n\t\t} else {\n\t\t\tconditions.push(sql`${ref} = ${value}`);\n\t\t}\n\t}\n\n\treturn conditions;\n}\n\n/**\n * Resolve a taxonomy filter (`name` + one or more `slug`s, optionally scoped to\n * `locale`) to the set of `translation_group`s the pivot stores in\n * `content_taxonomies.taxonomy_id`. Exact terms only — no subtree expansion.\n *\n * Mirrors the meaning of the old EXISTS join (`t.name = ? AND t.slug IN (?)\n * [AND t.locale = ?]`): a pivot row matches when its group has a term with that\n * name/slug in the active locale. Resolving to explicit values (rather than an\n * `IN (subquery)`) keeps the single-term case a plain equality on the pivot\n * index, which is what gives the clean early-`LIMIT` seek.\n */\nasync function resolveTermGroups(\n\tdb: Kysely<Database>,\n\tname: string,\n\tslugs: string[],\n\tlocale: string | undefined,\n): Promise<string[]> {\n\tlet query = db\n\t\t.selectFrom(\"taxonomies\")\n\t\t.select(\"translation_group\")\n\t\t.distinct()\n\t\t.where(\"name\", \"=\", name)\n\t\t.where(\"slug\", \"in\", slugs);\n\tif (locale) query = query.where(\"locale\", \"=\", locale);\n\tconst rows = await query.execute();\n\tconst groups = new Set<string>();\n\tfor (const row of rows) {\n\t\tif (row.translation_group) groups.add(row.translation_group);\n\t}\n\treturn [...groups];\n}\n\n/** Equality (single) or `IN` (multiple) condition on a pivot group column. */\nfunction pivotGroupCondition(ref: string, groups: string[]): ReturnType<typeof sql> {\n\tif (groups.length === 1) return sql`${sql.ref(ref)} = ${groups[0]}`;\n\treturn sql`${sql.ref(ref)} IN (${sql.join(groups.map((g) => sql`${g}`))})`;\n}\n\n/** LIMIT/OFFSET fragment matching the loader's single-table variant. */\nfunction buildPivotLimitOffset(\n\t// eslint-disable-next-line @typescript-eslint/no-explicit-any -- any Kysely instance\n\tdb: Kysely<any>,\n\tfetchLimit: number | undefined,\n\toffset: number | undefined,\n): ReturnType<typeof sql> {\n\tif (fetchLimit != null && offset != null) return sql`LIMIT ${fetchLimit} OFFSET ${offset}`;\n\tif (fetchLimit != null) return sql`LIMIT ${fetchLimit}`;\n\tif (offset != null) {\n\t\treturn isPostgres(db) ? sql`OFFSET ${offset}` : sql`LIMIT -1 OFFSET ${offset}`;\n\t}\n\treturn sql``;\n}\n\n/**\n * Options for {@link buildTaxonomyPivotQuery}.\n *\n * Parameterized on the `deletedIsNull` predicate and `status` condition so the\n * same builder serves the public live path (`deleted_at IS NULL` + published)\n * and, without any schema change, an admin trash (`deleted_at IS NOT\n * NULL`) or all-statuses shape. Admin wiring is out of scope today; the\n * parameters exist so `ContentRepository` can adopt this if it gains taxonomy\n * filtering.\n */\nexport interface TaxonomyPivotQueryOptions {\n\t// eslint-disable-next-line @typescript-eslint/no-explicit-any -- any Kysely instance\n\tdb: Kysely<any>;\n\t/** Collection slug (pivot `collection` value). */\n\tcollection: string;\n\t/** Content table name (`ec_<collection>`). */\n\ttableName: string;\n\t/**\n\t * Resolved translation_group sets, one per taxonomy filter. The first drives\n\t * the pivot seek; each additional set becomes a residual `EXISTS` (AND across\n\t * taxonomies). Multiple groups within a set are OR'd (dedup via GROUP BY).\n\t */\n\tgroupSets: string[][];\n\torderBy: OrderBySpec | undefined;\n\tcursor: string | undefined;\n\tlocale: string | undefined;\n\t/**\n\t * Status shape. A concrete value (`published`/`draft`/…) applies the same\n\t * condition `buildStatusCondition` produces (public: published only).\n\t * `undefined` drops the status filter entirely — the admin all-statuses shape.\n\t */\n\tstatus: string | undefined;\n\t/** `true` → `deleted_at IS NULL` (live); `false` → `IS NOT NULL` (trash). */\n\tdeletedIsNull: boolean;\n\t/** Byline translation_groups for an AND'd byline filter, or `null`. */\n\tbylineGroups: string[] | null;\n\tfetchLimit: number | undefined;\n\toffset: number | undefined;\n}\n\n/**\n * Build the pivot-driven taxonomy listing query (#1834).\n *\n * Drives from the term pivot and joins content translations through their\n * shared translation_group. Content columns remain authoritative for locale,\n * visibility, sorting, and cursor predicates.\n *\n * Two shapes:\n * - **Indexed sort** (`published_at`/`created_at`, single sort field): the\n *   `LIMIT` lives in `picked`.\n * - **Temp-sort** (`updated_at` or any other field, or multi-field sort): no\n *   pivot sort index applies, so `picked` collects the tagged candidate set and\n *   the outer query sorts the joined rows. Bounded to tagged rows — no\n *   `ec_*` full scan — but no early-`LIMIT`.\n */\nexport function buildTaxonomyPivotQuery(\n\topts: TaxonomyPivotQueryOptions,\n): ReturnType<typeof sql<Record<string, unknown>>> {\n\tconst {\n\t\tdb,\n\t\tcollection,\n\t\ttableName,\n\t\tgroupSets,\n\t\torderBy,\n\t\tcursor,\n\t\tlocale,\n\t\tstatus,\n\t\tdeletedIsNull,\n\t\tbylineGroups,\n\t\tfetchLimit,\n\t\toffset,\n\t} = opts;\n\n\tconst primary = getPrimarySort(orderBy);\n\tconst validSortKeys = orderBy\n\t\t? Object.keys(orderBy).filter((k) => FIELD_NAME_PATTERN.test(k))\n\t\t: [];\n\tconst singleSort = validSortKeys.length <= 1;\n\tconst isIndexedSort =\n\t\tsingleSort && (primary.field === \"published_at\" || primary.field === \"created_at\");\n\tconst dir = primary.direction === \"asc\" ? sql`ASC` : sql`DESC`;\n\tconst cmp = primary.direction === \"asc\" ? sql.raw(\">\") : sql.raw(\"<\");\n\n\tconst firstGroups = groupSets[0] ?? [];\n\tconst restGroups = groupSets.slice(1);\n\tconst multiGroup = firstGroups.length > 1;\n\n\t// Multi-term AND: one residual pivot-PK EXISTS per additional taxonomy.\n\tconst residual =\n\t\trestGroups.length > 0\n\t\t\t? sql`${sql.join(\n\t\t\t\t\trestGroups.map(\n\t\t\t\t\t\t(g) => sql`AND EXISTS (\n\t\t\t\t\t\tSELECT 1 FROM content_taxonomies ct2\n\t\t\t\t\t\tWHERE ct2.collection = ${collection}\n\t\t\t\t\t\t\tAND ct2.entry_id = ct.entry_id\n\t\t\t\t\t\t\tAND ${pivotGroupCondition(\"ct2.taxonomy_id\", g)}\n\t\t\t\t\t)`,\n\t\t\t\t\t),\n\t\t\t\t\tsql` `,\n\t\t\t\t)}`\n\t\t\t: sql``;\n\n\t// Byline assignments remain keyed to a locale-specific content row.\n\tconst bylineCt = bylineGroups\n\t\t? sql`AND EXISTS (\n\t\t\t\tSELECT 1 FROM _emdash_content_bylines cb\n\t\t\t\tWHERE cb.collection_slug = ${collection}\n\t\t\t\t\tAND cb.content_id = r.id\n\t\t\t\t\tAND cb.byline_id IN (${sql.join(bylineGroups.map((g) => sql`${g}`))})\n\t\t\t)`\n\t\t: sql``;\n\n\tconst firstGroupCond = pivotGroupCondition(\"ct.taxonomy_id\", firstGroups);\n\tconst pivotContentJoin = isPostgres(db) ? sql`JOIN` : sql`CROSS JOIN`;\n\tconst {\n\t\tterms: termsSelect,\n\t\tbylines: bylinesSelect,\n\t\tbylinesExist: bylinesExistSelect,\n\t} = foldedHydrationSelects(db, collection, \"r\");\n\n\t// Authoritative re-check on the joined `ec_*` row.\n\tconst deletedR = deletedIsNull ? sql`r.deleted_at IS NULL` : sql`r.deleted_at IS NOT NULL`;\n\tconst statusR = status !== undefined ? sql`AND ${buildStatusCondition(db, status, \"r\")}` : sql``;\n\tconst localeR = locale ? sql`AND r.locale = ${locale}` : sql``;\n\n\tif (isIndexedSort) {\n\t\tconst sortRef = sql.ref(`r.${primary.field}`);\n\t\tconst sortval = multiGroup ? sql`MAX(${sortRef})` : sortRef;\n\t\tconst groupByClause = multiGroup ? sql`GROUP BY r.id` : sql``;\n\n\t\tlet cursorClause = sql``;\n\t\tlet havingClause = sql``;\n\t\tif (cursor) {\n\t\t\tconst { orderValue, id } = decodeCursor(cursor);\n\t\t\tconst cond = sql`(${sortval} ${cmp} ${orderValue} OR (${sortval} = ${orderValue} AND r.id ${cmp} ${id}))`;\n\t\t\t// A GROUP BY makes `sortval` an aggregate → cursor goes in HAVING.\n\t\t\tif (multiGroup) havingClause = sql`HAVING ${cond}`;\n\t\t\telse cursorClause = sql`AND ${cond}`;\n\t\t}\n\n\t\tconst limitClause = buildPivotLimitOffset(db, fetchLimit, offset);\n\n\t\treturn sql<Record<string, unknown>>`\n\t\t\tWITH picked AS (\n\t\t\t\tSELECT r.id AS entry_id, ${sortval} AS sortval\n\t\t\t\tFROM content_taxonomies ct\n\t\t\t\t${pivotContentJoin} ${sql.ref(tableName)} AS r ON r.translation_group = ct.entry_id\n\t\t\t\tWHERE ct.collection = ${collection}\n\t\t\t\t\tAND ${firstGroupCond}\n\t\t\t\t\tAND ${deletedR}\n\t\t\t\t\t${statusR}\n\t\t\t\t\t${localeR}\n\t\t\t\t\t${residual}\n\t\t\t\t\t${bylineCt}\n\t\t\t\t\t${cursorClause}\n\t\t\t\t${groupByClause}\n\t\t\t\t${havingClause}\n\t\t\t\tORDER BY sortval ${dir}, r.id ${dir}\n\t\t\t\t${limitClause}\n\t\t\t)\n\t\t\tSELECT r.*, ${termsSelect}, ${bylinesSelect}, ${bylinesExistSelect}\n\t\t\tFROM picked JOIN ${sql.ref(tableName)} AS r ON r.id = picked.entry_id\n\t\t\tWHERE ${deletedR} ${statusR} ${localeR}\n\t\t\tORDER BY picked.sortval ${dir}, picked.entry_id ${dir}\n\t\t`;\n\t}\n\n\t// Temp-sort path: seek the term via the pivot, sort the joined candidate set.\n\tconst orderByClause = buildOrderByClause(orderBy, \"r\");\n\tconst cursorCond = cursor ? sql`AND ${buildCursorCondition(cursor, orderBy, \"r\")}` : sql``;\n\tconst limitClause = buildPivotLimitOffset(db, fetchLimit, offset);\n\treturn sql<Record<string, unknown>>`\n\t\tWITH picked AS (\n\t\t\tSELECT DISTINCT r.id AS entry_id\n\t\t\tFROM content_taxonomies ct\n\t\t\t${pivotContentJoin} ${sql.ref(tableName)} AS r ON r.translation_group = ct.entry_id\n\t\t\tWHERE ct.collection = ${collection}\n\t\t\t\tAND ${firstGroupCond}\n\t\t\t\tAND ${deletedR}\n\t\t\t\t${statusR}\n\t\t\t\t${localeR}\n\t\t\t\t${residual}\n\t\t\t\t${bylineCt}\n\t\t)\n\t\tSELECT r.*, ${termsSelect}, ${bylinesSelect}, ${bylinesExistSelect}\n\t\tFROM picked JOIN ${sql.ref(tableName)} AS r ON r.id = picked.entry_id\n\t\tWHERE ${deletedR} ${statusR} ${localeR}\n\t\t\t${cursorCond}\n\t\t${orderByClause}\n\t\t${limitClause}\n\t`;\n}\n\n/**\n * Range filter for comparison operators on field values.\n * Values are compared as strings in the database. This works correctly for\n * ISO 8601 dates (e.g. \"2024-01-01T00:00:00Z\") because lexicographic ordering\n * matches chronological ordering. Ensure date values use a consistent format.\n */\nexport interface WhereRange {\n\tgt?: string;\n\tgte?: string;\n\tlt?: string;\n\tlte?: string;\n}\n\n/**\n * A where clause value: exact match, multi-value match, or range comparison.\n */\nexport type WhereValue = string | string[] | WhereRange;\n\n/**\n * Fields shared by every collection filter, independent of pagination mode.\n *\n * Cursor and offset pagination are mutually exclusive, so they live on the\n * `CursorCollectionFilter` / `OffsetCollectionFilter` variants rather than\n * here. Use the {@link CollectionFilter} union for any value that may be\n * either.\n */\nexport interface CollectionFilterBase {\n\ttype: string;\n\tstatus?: \"draft\" | \"published\" | \"archived\";\n\tlimit?: number;\n\t/**\n\t * Filter by field values, taxonomy terms, byline credits, or ranges.\n\t *\n\t * Taxonomy names are detected automatically and filtered via JOIN.\n\t * The reserved `byline` key filters by byline credit (any credit, not\n\t * just the primary one) via the `_emdash_content_bylines` junction\n\t * table; its value is one or more byline translation groups.\n\t * Other keys are treated as column filters on the content table.\n\t *\n\t * @example { category: 'news' } - taxonomy term\n\t * @example { byline: '01HXYZ...' } - entries credited to a byline (any position)\n\t * @example { series: 'main' } - exact match on a content field\n\t * @example { published_at: { gte: '2024-01-01', lt: '2025-01-01' } } - date range\n\t */\n\twhere?: Record<string, WhereValue>;\n\t/**\n\t * Order results by field(s)\n\t * @default { created_at: \"desc\" }\n\t */\n\torderBy?: OrderBySpec;\n\t/**\n\t * Filter by locale (e.g. 'en', 'fr').\n\t * When set, only returns content in this locale.\n\t */\n\tlocale?: string;\n}\n\n/** Keyset-paginated collection filter. Cannot also carry an `offset`. */\nexport interface CursorCollectionFilter extends CollectionFilterBase {\n\t/**\n\t * Opaque cursor for keyset pagination.\n\t * Pass the `nextCursor` value from a previous result to fetch the next page.\n\t */\n\tcursor?: string;\n\toffset?: never;\n}\n\n/** Offset-paginated collection filter. Cannot also carry a `cursor`. */\nexport interface OffsetCollectionFilter extends CollectionFilterBase {\n\t/**\n\t * Skip this many rows before returning results (offset pagination).\n\t * Use with `limit` for numbered archive routes (`/page/2`):\n\t * `offset = (page - 1) * perPage`. Ignored unless it is a positive\n\t * integer.\n\t */\n\toffset?: number;\n\tcursor?: never;\n}\n\n/**\n * Filter for loadCollection - type is required.\n *\n * A union of the cursor and offset pagination variants: supplying both\n * `cursor` and `offset` is a compile-time error, since they are mutually\n * exclusive ways to express \"the next page\" (cursor wins at runtime).\n */\nexport type CollectionFilter = CursorCollectionFilter | OffsetCollectionFilter;\n\n/**\n * Filter for loadEntry - type and id are required\n */\nexport interface EntryFilter {\n\ttype: string;\n\tid: string;\n\t/**\n\t * When set, fetch content data from this revision instead of the content table.\n\t * Used by preview mode to serve draft revision data.\n\t */\n\trevisionId?: string;\n\t/**\n\t * Locale to scope slug lookup. Only affects slug resolution;\n\t * IDs are globally unique and always resolve regardless of locale.\n\t */\n\tlocale?: string;\n}\n\n// Cached database instance (shared across calls)\nlet dbInstance: Kysely<Database> | null = null;\n\n/**\n * Get the database instance. Used by query wrapper functions and middleware.\n *\n * Checks the ALS request context first — if a per-request DB override is set\n * (e.g. by DO preview middleware), it takes precedence over the module-level\n * cached instance. This allows preview mode to route queries to an isolated\n * Durable Object database without modifying any calling code.\n *\n * Initializes the default database on first call using config from virtual module.\n */\nexport async function getDb(): Promise<Kysely<Database>> {\n\t// Per-request DB override via ALS (normal mode)\n\tconst ctx = getRequestContext();\n\tif (ctx?.db) {\n\t\treturn ctx.db as Kysely<Database>; // eslint-disable-line typescript/no-unsafe-type-assertion -- db is typed as unknown in RequestContext to avoid circular deps\n\t}\n\n\tif (!dbInstance) {\n\t\tawait loadVirtualModules();\n\t\tif (!virtualConfig?.database || typeof virtualCreateDialect !== \"function\") {\n\t\t\tthrow new Error(\n\t\t\t\t\"EmDash database not configured. Add database config to emdash() in astro.config.mjs\",\n\t\t\t);\n\t\t}\n\t\tconst dialect = virtualCreateDialect(virtualConfig.database.config);\n\t\tdbInstance = new Kysely<Database>({ dialect, log: kyselyLogOption() });\n\t}\n\treturn dbInstance;\n}\n\n/**\n * Create an EmDash Live Collections loader\n *\n * This loader handles ALL content types in a single Astro collection.\n * Use `getEmDashCollection()` and `getEmDashEntry()` to query\n * specific content types.\n *\n * Database is configured in astro.config.mjs via the emdash() integration.\n *\n * @example\n * ```ts\n * // src/live.config.ts\n * import { defineLiveCollection } from \"astro:content\";\n * import { emdashLoader } from \"@premium-cms/emdash\";\n *\n * export const collections = {\n *   emdash: defineLiveCollection({\n *     loader: emdashLoader(),\n *   }),\n * };\n * ```\n */\nexport function emdashLoader(): LiveLoader<EntryData, EntryFilter, CollectionFilter> {\n\treturn {\n\t\tname: \"@premium-cms/emdash\",\n\n\t\t/**\n\t\t * Load all entries for a content type\n\t\t */\n\t\tasync loadCollection({ filter }) {\n\t\t\ttry {\n\t\t\t\t// Get DB instance (initializes on first use)\n\t\t\t\tconst db = await getDb();\n\n\t\t\t\t// Type filter is required\n\t\t\t\tconst type = filter?.type;\n\t\t\t\tif (!type) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\terror: new Error(\n\t\t\t\t\t\t\t\"type filter is required. Use getEmDashCollection() instead of getLiveCollection() directly.\",\n\t\t\t\t\t\t),\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\t// Query the per-collection table (ec_posts, ec_products, etc.)\n\t\t\t\tconst tableName = getTableName(type);\n\n\t\t\t\t// Build query with dynamic table name\n\t\t\t\tconst status = filter?.status || \"published\";\n\t\t\t\tconst limit = filter?.limit;\n\t\t\t\tconst cursor = filter?.cursor;\n\t\t\t\tconst where = filter?.where;\n\t\t\t\tconst orderBy = filter?.orderBy;\n\t\t\t\tconst locale = filter?.locale;\n\n\t\t\t\t// Cursor pagination: over-fetch by 1 to detect next page\n\t\t\t\tconst fetchLimit = limit ? limit + 1 : undefined;\n\n\t\t\t\t// Offset pagination (numbered archive routes). Keyset (cursor)\n\t\t\t\t// and offset are mutually exclusive ways to express \"the next\n\t\t\t\t// page\" — when both are supplied, cursor wins and offset is\n\t\t\t\t// dropped so the two don't stack into a double skip. Only a\n\t\t\t\t// positive integer applies; 0 / negative / fractional are no-ops.\n\t\t\t\tconst rawOffset = cursor ? undefined : filter?.offset;\n\t\t\t\tconst offset =\n\t\t\t\t\ttypeof rawOffset === \"number\" && Number.isInteger(rawOffset) && rawOffset > 0\n\t\t\t\t\t\t? rawOffset\n\t\t\t\t\t\t: undefined;\n\n\t\t\t\t// Build cursor condition if cursor is provided\n\t\t\t\tconst cursorCondition = cursor ? buildCursorCondition(cursor, orderBy) : null;\n\n\t\t\t\t// Separate taxonomy / byline filters from field filters\n\t\t\t\tlet result: { rows: Record<string, unknown>[] };\n\t\t\t\t// Taxonomy filters AND together: each entry constrains the base\n\t\t\t\t// row to match at least one of its slugs *within that taxonomy*.\n\t\t\t\t// Term slugs are unique only within a taxonomy, so every filter\n\t\t\t\t// keeps its own `name` and emits its own `EXISTS` clause rather\n\t\t\t\t// than pooling slugs into one `IN`.\n\t\t\t\tconst taxonomyFilters: { name: string; slugs: string[] }[] = [];\n\t\t\t\t// A byline filter matches entries credited to any of the given\n\t\t\t\t// byline translation groups via the `_emdash_content_bylines`\n\t\t\t\t// junction table. `null` means no byline filter; an empty\n\t\t\t\t// `groups` array means the filter was requested but matches\n\t\t\t\t// nothing (short-circuited to an empty result below).\n\t\t\t\tlet bylineFilter: { groups: string[] } | null = null;\n\t\t\t\tconst fieldFilters: Record<string, WhereValue> = {};\n\n\t\t\t\tif (where && Object.keys(where).length > 0) {\n\t\t\t\t\tconst taxNames = await getTaxonomyNames(db, type);\n\n\t\t\t\t\tfor (const [key, value] of Object.entries(where)) {\n\t\t\t\t\t\tif (value == null) continue;\n\t\t\t\t\t\tif (key === \"byline\") {\n\t\t\t\t\t\t\tif (isWhereRange(value)) {\n\t\t\t\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t\t\t\t`[emdash] where filter: range operators are not supported on \"byline\", ignored`,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst groups = Array.isArray(value) ? value : [value];\n\t\t\t\t\t\t\tbylineFilter = { groups };\n\t\t\t\t\t\t} else if (taxNames.has(key)) {\n\t\t\t\t\t\t\tif (isWhereRange(value)) {\n\t\t\t\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t\t\t\t`[emdash] where filter: range operators are not supported on taxonomy \"${key}\", ignored`,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst slugs = Array.isArray(value) ? value : [value];\n\t\t\t\t\t\t\ttaxonomyFilters.push({ name: key, slugs });\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tfieldFilters[key] = value;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// A byline or taxonomy filter with no values matches nothing —\n\t\t\t\t// short-circuit before building SQL (an empty `IN ()` is invalid\n\t\t\t\t// SQL on both dialects).\n\t\t\t\tif (\n\t\t\t\t\t(bylineFilter && bylineFilter.groups.length === 0) ||\n\t\t\t\t\ttaxonomyFilters.some((f) => f.slugs.length === 0)\n\t\t\t\t) {\n\t\t\t\t\treturn { entries: [], cacheHint: { tags: [type] } };\n\t\t\t\t}\n\n\t\t\t\tif (taxonomyFilters.length > 0 && Object.keys(fieldFilters).length === 0) {\n\t\t\t\t\t// Pivot-drive fast path (#1834): seek the matching entries on the\n\t\t\t\t\t// denormalized `content_taxonomies` pivot instead of scanning the\n\t\t\t\t\t// whole collection and probing a taxonomy EXISTS per row. Only the\n\t\t\t\t\t// taxonomy path is restructured — a taxonomy filter combined with a\n\t\t\t\t\t// content-field filter falls through to the single-table shape\n\t\t\t\t\t// below (field predicates live on `ec_*`, not the pivot). A byline\n\t\t\t\t\t// filter rides along inside the pivot CTE (see the builder).\n\t\t\t\t\tconst groupSets: string[][] = [];\n\t\t\t\t\tfor (const taxFilter of taxonomyFilters) {\n\t\t\t\t\t\tconst groups = await resolveTermGroups(db, taxFilter.name, taxFilter.slugs, locale);\n\t\t\t\t\t\t// A slug that resolves to no term matches nothing; since taxonomy\n\t\t\t\t\t\t// filters AND together, one empty set empties the whole result.\n\t\t\t\t\t\tif (groups.length === 0) {\n\t\t\t\t\t\t\treturn { entries: [], cacheHint: { tags: [type] } };\n\t\t\t\t\t\t}\n\t\t\t\t\t\tgroupSets.push(groups);\n\t\t\t\t\t}\n\n\t\t\t\t\tresult = await buildTaxonomyPivotQuery({\n\t\t\t\t\t\tdb,\n\t\t\t\t\t\tcollection: type,\n\t\t\t\t\t\ttableName,\n\t\t\t\t\t\tgroupSets,\n\t\t\t\t\t\torderBy,\n\t\t\t\t\t\tcursor,\n\t\t\t\t\t\tlocale,\n\t\t\t\t\t\tstatus,\n\t\t\t\t\t\t// Public listings only ever want live content.\n\t\t\t\t\t\tdeletedIsNull: true,\n\t\t\t\t\t\tbylineGroups: bylineFilter ? bylineFilter.groups : null,\n\t\t\t\t\t\tfetchLimit,\n\t\t\t\t\t\toffset,\n\t\t\t\t\t}).execute(db);\n\t\t\t\t} else {\n\t\t\t\t\t// Taxonomy and byline filters are applied as correlated\n\t\t\t\t\t// `EXISTS` semi-joins rather than `INNER JOIN ... DISTINCT`.\n\t\t\t\t\t// A join fan-out would force `SELECT DISTINCT table.*`, and\n\t\t\t\t\t// Postgres cannot apply DISTINCT to a row containing a `json`\n\t\t\t\t\t// column (no equality operator), so the join approach throws\n\t\t\t\t\t// there. EXISTS matches \"credited/tagged at least once\"\n\t\t\t\t\t// without duplicating rows, needs no DISTINCT, and works on\n\t\t\t\t\t// both SQLite and Postgres. The base query stays a single-\n\t\t\t\t\t// table `SELECT *`, so all field/status/locale/cursor/order\n\t\t\t\t\t// conditions reference unprefixed columns as before.\n\t\t\t\t\tconst orderByClause = buildOrderByClause(orderBy);\n\t\t\t\t\tconst statusCondition = buildStatusCondition(db, status);\n\t\t\t\t\tconst localeFilter = locale ? sql`AND locale = ${locale}` : sql``;\n\t\t\t\t\tconst cursorCond = cursorCondition ? sql`AND ${cursorCondition}` : sql``;\n\t\t\t\t\tconst fieldConds = buildFieldConditions(fieldFilters);\n\t\t\t\t\tconst fieldCondsSQL =\n\t\t\t\t\t\tfieldConds.length > 0 ? sql`${sql.join(fieldConds, sql` AND `)}` : null;\n\n\t\t\t\t\t// One `EXISTS` per taxonomy, AND'd together: an entry must be\n\t\t\t\t\t// tagged with a matching term in *every* requested taxonomy.\n\t\t\t\t\t// Each clause pins its own `t.name`, so slugs never pool\n\t\t\t\t\t// across taxonomies (they're only unique within one).\n\t\t\t\t\tconst taxonomyCond =\n\t\t\t\t\t\ttaxonomyFilters.length > 0\n\t\t\t\t\t\t\t? sql`${sql.join(\n\t\t\t\t\t\t\t\t\ttaxonomyFilters.map(\n\t\t\t\t\t\t\t\t\t\t(f) => sql`AND EXISTS (\n\t\t\t\t\t\t\tSELECT 1 FROM content_taxonomies ct\n\t\t\t\t\t\t\tINNER JOIN taxonomies t ON t.translation_group = ct.taxonomy_id\n\t\t\t\t\t\t\tWHERE ct.collection = ${type}\n\t\t\t\t\t\t\t\tAND ct.entry_id = ${sql.ref(tableName)}.translation_group\n\t\t\t\t\t\t\t\tAND t.name = ${f.name}\n\t\t\t\t\t\t\t\tAND t.slug IN (${sql.join(f.slugs.map((s) => sql`${s}`))})\n\t\t\t\t\t\t\t${locale ? sql`AND t.locale = ${locale}` : sql``}\n\t\t\t\t\t\t)`,\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\tsql` `,\n\t\t\t\t\t\t\t\t)}`\n\t\t\t\t\t\t\t: sql``;\n\n\t\t\t\t\t// `_emdash_content_bylines.byline_id` stores the byline's\n\t\t\t\t\t// translation_group (migration 040), so a credit spans every\n\t\t\t\t\t// locale variant of the byline and we match the group directly.\n\t\t\t\t\tconst bylineCond = bylineFilter\n\t\t\t\t\t\t? sql`AND EXISTS (\n\t\t\t\t\t\t\tSELECT 1 FROM _emdash_content_bylines cb\n\t\t\t\t\t\t\tWHERE cb.collection_slug = ${type}\n\t\t\t\t\t\t\t\tAND cb.content_id = ${sql.ref(tableName)}.id\n\t\t\t\t\t\t\t\tAND cb.byline_id IN (${sql.join(bylineFilter.groups.map((g) => sql`${g}`))})\n\t\t\t\t\t\t)`\n\t\t\t\t\t\t: sql``;\n\n\t\t\t\t\t// Fold byline + taxonomy hydration into the list query.\n\t\t\t\t\tconst {\n\t\t\t\t\t\tterms: termsSelect,\n\t\t\t\t\t\tbylines: bylinesSelect,\n\t\t\t\t\t\tbylinesExist: bylinesExistSelect,\n\t\t\t\t\t} = foldedHydrationSelects(db, type, tableName);\n\n\t\t\t\t\t// LIMIT/OFFSET clause. SQLite only accepts OFFSET when a\n\t\t\t\t\t// LIMIT is present, so a bare offset uses `LIMIT -1`\n\t\t\t\t\t// (unbounded); Postgres takes a standalone OFFSET.\n\t\t\t\t\tlet limitOffsetClause = sql``;\n\t\t\t\t\tif (fetchLimit != null && offset != null) {\n\t\t\t\t\t\tlimitOffsetClause = sql`LIMIT ${fetchLimit} OFFSET ${offset}`;\n\t\t\t\t\t} else if (fetchLimit != null) {\n\t\t\t\t\t\tlimitOffsetClause = sql`LIMIT ${fetchLimit}`;\n\t\t\t\t\t} else if (offset != null) {\n\t\t\t\t\t\tlimitOffsetClause = isPostgres(db)\n\t\t\t\t\t\t\t? sql`OFFSET ${offset}`\n\t\t\t\t\t\t\t: sql`LIMIT -1 OFFSET ${offset}`;\n\t\t\t\t\t}\n\t\t\t\t\tresult = await sql<Record<string, unknown>>`\n\t\t\t\t\t\tSELECT *, ${termsSelect}, ${bylinesSelect}, ${bylinesExistSelect} FROM ${sql.ref(tableName)}\n\t\t\t\t\t\tWHERE deleted_at IS NULL\n\t\t\t\t\t\tAND ${statusCondition}\n\t\t\t\t\t\t${localeFilter}\n\t\t\t\t\t\t${cursorCond}\n\t\t\t\t\t\t${taxonomyCond}\n\t\t\t\t\t\t${bylineCond}\n\t\t\t\t\t\t${fieldCondsSQL ? sql`AND ${fieldCondsSQL}` : sql``}\n\t\t\t\t\t\t${orderByClause}\n\t\t\t\t\t\t${limitOffsetClause}\n\t\t\t\t\t`.execute(db);\n\t\t\t\t}\n\n\t\t\t\t// Detect whether there are more results (over-fetched by 1)\n\t\t\t\tconst hasMore = limit ? result.rows.length > limit : false;\n\t\t\t\tconst rows = hasMore ? result.rows.slice(0, limit) : result.rows;\n\n\t\t\t\t// Map rows to entries\n\t\t\t\tconst i18nConfig = virtualConfig?.i18n;\n\t\t\t\tconst i18nEnabled = i18nConfig && i18nConfig.locales.length > 1;\n\t\t\t\tconst entries = rows.map((row) => {\n\t\t\t\t\tconst slug = rowStr(row, \"slug\") || rowStr(row, \"id\");\n\t\t\t\t\tconst rowLocale = rowStr(row, \"locale\");\n\t\t\t\t\tconst shouldPrefix =\n\t\t\t\t\t\ti18nEnabled &&\n\t\t\t\t\t\trowLocale !== \"\" &&\n\t\t\t\t\t\t(rowLocale !== i18nConfig.defaultLocale || i18nConfig.prefixDefaultLocale);\n\t\t\t\t\tconst id = shouldPrefix ? `${rowLocale}/${slug}` : slug;\n\t\t\t\t\tconst data = mapRowToData(row);\n\t\t\t\t\tstashFolded(data, row);\n\t\t\t\t\treturn {\n\t\t\t\t\t\tid,\n\t\t\t\t\t\tslug: rowStr(row, \"slug\"),\n\t\t\t\t\t\tstatus: rowStr(row, \"status\", \"draft\"),\n\t\t\t\t\t\tdata,\n\t\t\t\t\t\tcacheHint: {\n\t\t\t\t\t\t\ttags: [rowStr(row, \"id\")],\n\t\t\t\t\t\t\tlastModified: row.updated_at ? new Date(rowStr(row, \"updated_at\")) : undefined,\n\t\t\t\t\t\t},\n\t\t\t\t\t};\n\t\t\t\t});\n\n\t\t\t\t// Encode nextCursor from the last row if there are more results\n\t\t\t\tlet nextCursor: string | undefined;\n\t\t\t\tif (hasMore && rows.length > 0) {\n\t\t\t\t\tconst lastRow = rows.at(-1)!;\n\t\t\t\t\tconst primary = getPrimarySort(orderBy);\n\t\t\t\t\t// Strip table prefix from field name for row lookup\n\t\t\t\t\tconst fieldName = primary.field.includes(\".\")\n\t\t\t\t\t\t? primary.field.split(\".\").pop()!\n\t\t\t\t\t\t: primary.field;\n\t\t\t\t\tconst lastOrderValue = lastRow[fieldName];\n\t\t\t\t\tconst orderStr =\n\t\t\t\t\t\ttypeof lastOrderValue === \"string\" || typeof lastOrderValue === \"number\"\n\t\t\t\t\t\t\t? String(lastOrderValue)\n\t\t\t\t\t\t\t: \"\";\n\t\t\t\t\tnextCursor = encodeCursor(orderStr, String(lastRow.id));\n\t\t\t\t}\n\n\t\t\t\t// Collection-level cache hint uses the most recent updated_at\n\t\t\t\tlet collectionLastModified: Date | undefined;\n\t\t\t\tfor (const row of rows) {\n\t\t\t\t\tif (row.updated_at) {\n\t\t\t\t\t\tconst d = new Date(rowStr(row, \"updated_at\"));\n\t\t\t\t\t\tif (!collectionLastModified || d > collectionLastModified) {\n\t\t\t\t\t\t\tcollectionLastModified = d;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn {\n\t\t\t\t\tentries,\n\t\t\t\t\tnextCursor,\n\t\t\t\t\tcacheHint: {\n\t\t\t\t\t\ttags: [type],\n\t\t\t\t\t\tlastModified: collectionLastModified,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t} catch (error) {\n\t\t\t\t// Handle missing table/column gracefully - return empty collection.\n\t\t\t\t// Missing table happens before migrations have run.\n\t\t\t\t// Missing column happens when a where filter references a non-existent field.\n\t\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\t\tif (isMissingTableError(error) || isMissingColumnError(error)) {\n\t\t\t\t\tif (isMissingColumnError(error)) {\n\t\t\t\t\t\tconsole.warn(`[emdash] where filter: ${message}`);\n\t\t\t\t\t}\n\t\t\t\t\treturn { entries: [] };\n\t\t\t\t}\n\n\t\t\t\treturn {\n\t\t\t\t\terror: new Error(`Failed to load collection: ${message}`),\n\t\t\t\t};\n\t\t\t}\n\t\t},\n\n\t\t/**\n\t\t * Load a single entry by type and ID/slug\n\t\t *\n\t\t * When filter.revisionId is set (preview mode), the entry's data\n\t\t * comes from the revisions table instead of the content table columns.\n\t\t */\n\t\tasync loadEntry({ filter }) {\n\t\t\ttry {\n\t\t\t\t// Get DB instance\n\t\t\t\tconst db = await getDb();\n\n\t\t\t\t// Both type and id are required\n\t\t\t\tconst type = filter?.type;\n\t\t\t\tconst id = filter?.id;\n\n\t\t\t\tif (!type || !id) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\terror: new Error(\n\t\t\t\t\t\t\t\"type and id filters are required. Use getEmDashEntry() instead of getLiveEntry() directly.\",\n\t\t\t\t\t\t),\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\t// Query the per-collection table\n\t\t\t\tconst tableName = getTableName(type);\n\t\t\t\tconst locale = filter?.locale;\n\n\t\t\t\t// Use raw SQL for dynamic table name, match by slug or id\n\t\t\t\t// When locale is specified, prefer locale-scoped slug match,\n\t\t\t\t// but IDs are globally unique so always check id without locale scope.\n\t\t\t\t//\n\t\t\t\t// Byline + taxonomy hydration (foldedHydrationSelects) and per-entry\n\t\t\t\t// SEO (foldedSeoSelect) are each surfaced as a single aggregated JSON\n\t\t\t\t// column rather than flat columns. This keeps the result-set width\n\t\t\t\t// bounded at any collection schema width: a flat `LEFT JOIN _emdash_seo`\n\t\t\t\t// adds 5 alias columns to every row and pushes wide flat-schema\n\t\t\t\t// collections (common after WordPress / ACF imports) past D1's\n\t\t\t\t// per-result-set column limit, surfacing as a silent null entry. One\n\t\t\t\t// JSON column is one column, so the join stays safe at any width and\n\t\t\t\t// we keep the single round trip.\n\t\t\t\tconst {\n\t\t\t\t\tterms: termsSelect,\n\t\t\t\t\tbylines: bylinesSelect,\n\t\t\t\t\tbylinesExist: bylinesExistSelect,\n\t\t\t\t} = foldedHydrationSelects(db, type, \"c\");\n\t\t\t\tconst seoSelect = foldedSeoSelect(db, type, \"c\");\n\t\t\t\tconst result = locale\n\t\t\t\t\t? await sql<Record<string, unknown>>`\n\t\t\t\t\t\t\tSELECT c.*, ${seoSelect}, ${termsSelect}, ${bylinesSelect}, ${bylinesExistSelect}\n\t\t\t\t\t\t\tFROM ${sql.ref(tableName)} AS c\n\t\t\t\t\t\t\tWHERE c.deleted_at IS NULL\n\t\t\t\t\t\t\tAND ((c.slug = ${id} AND c.locale = ${locale}) OR c.id = ${id})\n\t\t\t\t\t\t\tLIMIT 1\n\t\t\t\t\t\t`.execute(db)\n\t\t\t\t\t: await sql<Record<string, unknown>>`\n\t\t\t\t\t\t\tSELECT c.*, ${seoSelect}, ${termsSelect}, ${bylinesSelect}, ${bylinesExistSelect}\n\t\t\t\t\t\t\tFROM ${sql.ref(tableName)} AS c\n\t\t\t\t\t\t\tWHERE c.deleted_at IS NULL\n\t\t\t\t\t\t\tAND (c.slug = ${id} OR c.id = ${id})\n\t\t\t\t\t\t\tLIMIT 1\n\t\t\t\t\t\t`.execute(db);\n\n\t\t\t\tconst row = result.rows[0];\n\t\t\t\tif (!row) {\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\n\t\t\t\t// Expand the folded SEO JSON column onto SEO_COLUMN_ALIASES so\n\t\t\t\t// extractSeo() reads it transparently. Missing/null SEO is a\n\t\t\t\t// no-op: extractSeo() returns null when the aliases are absent.\n\t\t\t\texpandFoldedSeo(row);\n\n\t\t\t\tconst i18nConfig = virtualConfig?.i18n;\n\t\t\t\tconst i18nEnabled = i18nConfig && i18nConfig.locales.length > 1;\n\t\t\t\tconst entrySlug = rowStr(row, \"slug\") || rowStr(row, \"id\");\n\t\t\t\tconst entryLocale = rowStr(row, \"locale\");\n\t\t\t\tconst shouldPrefixEntry =\n\t\t\t\t\ti18nEnabled &&\n\t\t\t\t\tentryLocale !== \"\" &&\n\t\t\t\t\t(entryLocale !== i18nConfig.defaultLocale || i18nConfig.prefixDefaultLocale);\n\t\t\t\tconst entryId = shouldPrefixEntry ? `${entryLocale}/${entrySlug}` : entrySlug;\n\n\t\t\t\t// Preview mode: override content fields with revision data,\n\t\t\t\t// keeping system metadata from the content table row.\n\t\t\t\tconst revisionId = filter?.revisionId;\n\t\t\t\tif (revisionId) {\n\t\t\t\t\tconst revRow = await sql<{ data: string }>`\n\t\t\t\t\t\tSELECT data FROM revisions\n\t\t\t\t\t\tWHERE id = ${revisionId}\n\t\t\t\t\t\tLIMIT 1\n\t\t\t\t\t`.execute(db);\n\n\t\t\t\t\tconst revData = revRow.rows[0];\n\t\t\t\t\tif (revData) {\n\t\t\t\t\t\tconst parsed: Record<string, unknown> = JSON.parse(revData.data);\n\t\t\t\t\t\t// System metadata from content table + content fields from revision\n\t\t\t\t\t\tconst systemData: Record<string, unknown> = {};\n\t\t\t\t\t\tfor (const [key, mappedKey] of Object.entries(INCLUDE_IN_DATA)) {\n\t\t\t\t\t\t\tif (key in row) {\n\t\t\t\t\t\t\t\tif (DATE_COLUMNS.has(key)) {\n\t\t\t\t\t\t\t\t\tsystemData[mappedKey] = typeof row[key] === \"string\" ? new Date(row[key]) : null;\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tsystemData[mappedKey] = row[key];\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Use slug from revision metadata if present, else from content table\n\t\t\t\t\t\tconst slug = typeof parsed._slug === \"string\" ? parsed._slug : rowStr(row, \"slug\");\n\t\t\t\t\t\tconst revSlug = slug || rowStr(row, \"id\");\n\t\t\t\t\t\tconst revLocale = rowStr(row, \"locale\");\n\t\t\t\t\t\tconst shouldPrefixRev =\n\t\t\t\t\t\t\ti18nEnabled &&\n\t\t\t\t\t\t\trevLocale !== \"\" &&\n\t\t\t\t\t\t\t(revLocale !== i18nConfig.defaultLocale || i18nConfig.prefixDefaultLocale);\n\t\t\t\t\t\tconst revId = shouldPrefixRev ? `${revLocale}/${revSlug}` : revSlug;\n\t\t\t\t\t\t// SEO is not revisioned — it comes from the content row's\n\t\t\t\t\t\t// joined _emdash_seo columns, not the revision snapshot.\n\t\t\t\t\t\tconst revEntryData: Record<string, unknown> = {\n\t\t\t\t\t\t\t...systemData,\n\t\t\t\t\t\t\tslug,\n\t\t\t\t\t\t\t...mapRevisionData(parsed),\n\t\t\t\t\t\t};\n\t\t\t\t\t\tconst revSeo = extractSeo(row);\n\t\t\t\t\t\tif (revSeo) revEntryData.seo = revSeo;\n\t\t\t\t\t\tstashFolded(revEntryData, row);\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tid: revId,\n\t\t\t\t\t\t\tslug,\n\t\t\t\t\t\t\tstatus: rowStr(row, \"status\", \"draft\"),\n\t\t\t\t\t\t\tdata: revEntryData,\n\t\t\t\t\t\t\tcacheHint: {\n\t\t\t\t\t\t\t\ttags: [rowStr(row, \"id\")],\n\t\t\t\t\t\t\t\tlastModified: row.updated_at ? new Date(rowStr(row, \"updated_at\")) : undefined,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst entryData = mapRowToData(row);\n\t\t\t\tconst entrySeo = extractSeo(row);\n\t\t\t\tif (entrySeo) entryData.seo = entrySeo;\n\t\t\t\tstashFolded(entryData, row);\n\t\t\t\treturn {\n\t\t\t\t\tid: entryId,\n\t\t\t\t\tslug: rowStr(row, \"slug\"),\n\t\t\t\t\tstatus: rowStr(row, \"status\", \"draft\"),\n\t\t\t\t\tdata: entryData,\n\t\t\t\t\tcacheHint: {\n\t\t\t\t\t\ttags: [rowStr(row, \"id\")],\n\t\t\t\t\t\tlastModified: row.updated_at ? new Date(rowStr(row, \"updated_at\")) : undefined,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t} catch (error) {\n\t\t\t\t// Handle missing table gracefully - return undefined (not found).\n\t\t\t\t// This happens before migrations have run.\n\t\t\t\tif (isMissingTableError(error)) {\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\n\t\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\t\treturn {\n\t\t\t\t\terror: new Error(`Failed to load entry: ${message}`),\n\t\t\t\t};\n\t\t\t}\n\t\t},\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAyBA,MAAM,qBAAqB;;;;;;;;;;;;;;;;;;;;;AAsB3B,MAAM,qBAA6C;CAClD,WAAW;CACX,iBAAiB;CACjB,WAAW;CACX,eAAe;CACf,cAAc;CACd;;AAGD,MAAM,oBAAoB,OAAO,OAAO,mBAAmB;;AAG3D,MAAM,oBAAoB;;;;;AAM1B,MAAM,iBAAiB,IAAI,IAAI;CAC9B;CAEA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAKA,GAAG;CAIH;CACA;CACA;CACA;CACA,CAAC;;AAGF,MAAa,eAAe,OAAO,IAAI,qBAAqB;AAC5D,MAAa,iBAAiB,OAAO,IAAI,uBAAuB;;;;;;AAMhE,MAAa,uBAAuB,OAAO,IAAI,4BAA4B;;;;;;;;;;;;;AAe3E,SAAS,uBAAuB,IAAiB,MAAc,OAAe;CAC7E,MAAM,IAAI,IAAI,IAAI,MAAM;CACxB,MAAM,KAAK,WAAW,GAAG;CACzB,MAAM,OAAO,UACZ,KAAK,IAAI,IAAI,qBAAqB,MAAM,GAAG,GAAG,IAAI,IAAI,eAAe,MAAM,GAAG;CAC/E,MAAM,OAAO,UACZ,KAAK,GAAG,qBAAqB,MAAM,kBAAkB,GAAG,oBAAoB,MAAM;CAOnF,MAAM,WAAW,KAAK,GAAG,SAAS,GAAG;CAErC,MAAM,UAAU,IACf,obACA;CACD,MAAM,gBAAgB,eAAe,EAAE,iBAAiB;CACxD,MAAM,iBAAiB,GAAG;CAI1B,MAAM,QAAQ,GAAG,WAHD,KACb,GAAG,qBAAqB,QAAQ,kBAAkB,eAAe,8BACjE,GAAG,oBAAoB,QAAQ,kBAAkB,eAAe,eAC/B,QAAQ,IAAI,IAAI,qBAAqB,C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