{"version":3,"file":"wxr-taxonomies-CUIfJvM8.mjs","names":[],"sources":["../src/import/wxr-taxonomies.ts"],"sourcesContent":["/**\n * WXR taxonomy import helpers.\n *\n * Bridges parsed WordPress taxonomy data (`WxrCategory`, `WxrTag`, `WxrTerm`,\n * and per-item `WxrPost.categories` / `WxrPost.tags` / `WxrPost.customTaxonomies`)\n * onto EmDash's term + content_taxonomies tables.\n *\n * Why this isn't inline in `execute.ts`: pre-creating all terms before any\n * post is created lets us (a) build a lookup once for every (taxonomy, slug)\n * the import needs, and (b) keep the per-post attachment loop cheap. It also\n * makes the logic testable without spinning up an Astro request.\n *\n * Behaviour:\n *   - `wp:category` -> EmDash `category` taxonomy (seeded by migration 006).\n *   - `wp:tag`      -> EmDash `tag` taxonomy.\n *   - `wp:term`     -> matching EmDash taxonomy by `name` (case-sensitive).\n *                      If no matching def exists in the target locale, the\n *                      term is skipped — we don't auto-create defs because\n *                      the user controls their schema through the admin.\n *   - Terms are created idempotently by `(taxonomy, slug, locale)`. Existing\n *     terms are reused.\n *   - Assignments respect the def's `collections` array. If the post's target\n *     collection isn't listed on the taxonomy def, the assignment is skipped\n *     (matches admin UI behaviour: you can't tag a \"products\" post with a\n *     \"category\" if `category.collections` only includes \"posts\").\n */\n\nimport type { Kysely } from \"kysely\";\n\nimport type { WxrCategory, WxrPost, WxrTag, WxrTerm } from \"../cli/wxr/parser.js\";\nimport { TaxonomyRepository } from \"../database/repositories/taxonomy.js\";\nimport type { Database } from \"../database/types.js\";\nimport { resolveLocaleChain } from \"../i18n/resolve.js\";\nimport { invalidateTermCache } from \"../taxonomies/index.js\";\n\n/**\n * Thrown by `mirrorTermsToLocales` when a pre-existing locale row at the\n * same `(taxonomy, slug)` belongs to a different `translation_group` than\n * the canonical term. Callers in the route layer surface\n * `publicMessage` to the operator (no internal data) while logging\n * `cause` server-side.\n *\n * Marker class so the route layer can distinguish \"operator-actionable\n * taxonomy conflict\" from any other DB / repository error that might\n * escape the helper.\n */\nexport class WxrTaxonomyConflictError extends Error {\n\treadonly publicMessage: string;\n\tconstructor(publicMessage: string, options?: { cause?: unknown }) {\n\t\tsuper(publicMessage, options);\n\t\tthis.name = \"WxrTaxonomyConflictError\";\n\t\tthis.publicMessage = publicMessage;\n\t}\n}\n\nexport function isWxrTaxonomyConflictError(error: unknown): error is WxrTaxonomyConflictError {\n\treturn error instanceof WxrTaxonomyConflictError;\n}\n\n/**\n * Result of pre-importing taxonomy terms from a WXR file.\n */\nexport interface TaxonomyImportPlan {\n\t/** terms created during this run (per taxonomy name) */\n\ttermsCreated: Record<string, number>;\n\t/** terms that already existed and were reused (per taxonomy name) */\n\ttermsReused: Record<string, number>;\n\t/** custom taxonomies (`wp:term`) skipped because no matching EmDash def exists */\n\tmissingTaxonomies: string[];\n\t/**\n\t * Lookup table: `taxonomy name` -> `term slug` -> term id.\n\t * Used by `attachPostTaxonomies` to translate WXR assignments into pivot rows.\n\t */\n\ttermIdByNameAndSlug: Map<string, Map<string, string>>;\n\t/**\n\t * Lookup table: `taxonomy name` -> set of collection slugs the def allows.\n\t * Empty (or missing) means \"any collection\" — we only enforce the filter\n\t * when the def explicitly lists collections.\n\t */\n\tcollectionsByTaxonomy: Map<string, Set<string>>;\n\t/**\n\t * Lookup table: `term id` -> the term's `translation_group` (or `null`\n\t * if the term doesn't exist any more). Populated lazily by helpers that\n\t * need to check pivot existence without repeating per-term DB reads.\n\t */\n\ttranslationGroupByTermId: Map<string, string | null>;\n}\n\n/**\n * Track running counts plus the lookup maps.\n */\ninterface TaxonomyImportState {\n\tplan: TaxonomyImportPlan;\n}\n\nfunction makeState(): TaxonomyImportState {\n\treturn {\n\t\tplan: {\n\t\t\ttermsCreated: {},\n\t\t\ttermsReused: {},\n\t\t\tmissingTaxonomies: [],\n\t\t\ttermIdByNameAndSlug: new Map(),\n\t\t\tcollectionsByTaxonomy: new Map(),\n\t\t\ttranslationGroupByTermId: new Map(),\n\t\t},\n\t};\n}\n\n/**\n * Record-keeping helpers — keep mutations centralised so the result object\n * stays consistent.\n */\nfunction bump(record: Record<string, number>, key: string): void {\n\trecord[key] = (record[key] ?? 0) + 1;\n}\n\nfunction rememberTerm(\n\tstate: TaxonomyImportState,\n\ttaxonomyName: string,\n\tslug: string,\n\ttermId: string,\n): void {\n\tlet bySlug = state.plan.termIdByNameAndSlug.get(taxonomyName);\n\tif (!bySlug) {\n\t\tbySlug = new Map();\n\t\tstate.plan.termIdByNameAndSlug.set(taxonomyName, bySlug);\n\t}\n\tbySlug.set(slug, termId);\n}\n\n/**\n * Look up an EmDash taxonomy def by name. Definitions are per-locale but\n * a def is conceptually site-wide -- the per-locale row carries only the\n * label translations.\n *\n * Match the runtime helper `getTaxonomyDef` (in `src/taxonomies/index.ts`):\n * walk `resolveLocaleChain(locale)` so the importer picks the same def the\n * runtime would later resolve to. When the chain is empty (i18n disabled)\n * or every locale in the chain misses, fall through to the lowest-locale\n * row so single-locale installs still see seeded defs that were inserted\n * at some non-empty locale value.\n *\n * Without this fallback, a user importing into a non-default locale would\n * see every category dropped as `missingTaxonomies` even though the seeded\n * defs exist (just at the site's default locale).\n */\nfunction parseDefCollections(raw: string | null): string[] {\n\tif (!raw) return [];\n\ttry {\n\t\tconst parsed: unknown = JSON.parse(raw);\n\t\tif (Array.isArray(parsed)) {\n\t\t\treturn parsed.filter((c): c is string => typeof c === \"string\");\n\t\t}\n\t} catch {\n\t\t// malformed JSON in the def -- treat as \"no collection filter\"\n\t}\n\treturn [];\n}\n\nasync function findTaxonomyDef(\n\tdb: Kysely<Database>,\n\tname: string,\n\tlocale: string | undefined,\n): Promise<{ id: string; collections: string[] } | null> {\n\tconst chain = resolveLocaleChain(locale);\n\n\tif (chain.length === 0) {\n\t\t// i18n disabled and no explicit locale. The runtime treats this\n\t\t// as \"no locale filter\" and picks the lowest-locale row. We do the\n\t\t// same so the importer agrees with how the runtime later reads\n\t\t// the def.\n\t\tconst row = await db\n\t\t\t.selectFrom(\"_emdash_taxonomy_defs\")\n\t\t\t.selectAll()\n\t\t\t.where(\"name\", \"=\", name)\n\t\t\t.orderBy(\"locale\", \"asc\")\n\t\t\t.executeTakeFirst();\n\t\treturn row ? { id: row.id, collections: parseDefCollections(row.collections) } : null;\n\t}\n\n\t// Non-empty chain: walk it in order, return null if every entry misses.\n\t// This matches `getTaxonomyDef` exactly. We deliberately do NOT fall\n\t// through to any-locale lookup: doing so would let the importer pick a\n\t// def at a locale the runtime would never resolve to, producing\n\t// content the user can't see in the admin or on the rendered site.\n\tfor (const tryLocale of chain) {\n\t\tconst row = await db\n\t\t\t.selectFrom(\"_emdash_taxonomy_defs\")\n\t\t\t.selectAll()\n\t\t\t.where(\"name\", \"=\", name)\n\t\t\t.where(\"locale\", \"=\", tryLocale)\n\t\t\t.executeTakeFirst();\n\t\tif (row) {\n\t\t\treturn { id: row.id, collections: parseDefCollections(row.collections) };\n\t\t}\n\t}\n\n\treturn null;\n}\n\n/**\n * Rebuild the taxonomy lookup maps from the database without creating\n * anything. The chunked WP import runs term creation once (first content\n * chunk); every later chunk only needs the maps to attach per-post\n * assignments, and two SELECTs are far cheaper than re-walking every term\n * through the ensure path.\n *\n * ponytail: first row wins per (name, slug), ordered by locale asc — the\n * same row `findBySlug` without a locale resolves to. Per-locale term\n * variants beyond that are the mirror pass's job, not the importer's.\n */\nexport async function loadTaxonomyPlanFromDb(db: Kysely<Database>): Promise<TaxonomyImportPlan> {\n\tconst state = makeState();\n\n\tconst defs = await db\n\t\t.selectFrom(\"_emdash_taxonomy_defs\")\n\t\t.select([\"name\", \"collections\"])\n\t\t.orderBy(\"locale\", \"asc\")\n\t\t.execute();\n\tfor (const def of defs) {\n\t\tif (!state.plan.collectionsByTaxonomy.has(def.name)) {\n\t\t\tstate.plan.collectionsByTaxonomy.set(def.name, new Set(parseDefCollections(def.collections)));\n\t\t}\n\t}\n\n\tconst terms = await db\n\t\t.selectFrom(\"taxonomies\")\n\t\t.select([\"name\", \"slug\", \"id\"])\n\t\t.orderBy(\"locale\", \"asc\")\n\t\t.execute();\n\tfor (const term of terms) {\n\t\tif (!state.plan.termIdByNameAndSlug.get(term.name)?.has(term.slug)) {\n\t\t\trememberTerm(state, term.name, term.slug, term.id);\n\t\t}\n\t}\n\n\treturn state.plan;\n}\n\n/**\n * Find or create a term in the given taxonomy. Returns the term id. Callers\n * must verify the taxonomy def exists before calling — this helper assumes\n * the def is present.\n *\n * Note: we don't resolve WordPress parent slugs into EmDash parent ids in\n * this pass. WXR exports list categories in arbitrary order, so a category's\n * parent may not exist yet when we first see it. Hierarchy is preserved at\n * the data level (the parent slug is on `WxrCategory.parent`) but flattens\n * in EmDash for now; restoring the tree is a follow-up improvement.\n */\nasync function ensureTerm(\n\trepo: TaxonomyRepository,\n\tstate: TaxonomyImportState,\n\ttaxonomyName: string,\n\tslug: string,\n\tlabel: string,\n\tdescription: string | undefined,\n\tlocale: string | undefined,\n): Promise<string> {\n\t// Already resolved in this run (e.g. seen in `wp:category` AND in a per-\n\t// item `<category>` element).\n\tconst cached = state.plan.termIdByNameAndSlug.get(taxonomyName)?.get(slug);\n\tif (cached) return cached;\n\n\tconst existing = await repo.findBySlug(taxonomyName, slug, locale);\n\tif (existing) {\n\t\tbump(state.plan.termsReused, taxonomyName);\n\t\trememberTerm(state, taxonomyName, slug, existing.id);\n\t\treturn existing.id;\n\t}\n\n\t// No row at the requested locale. Before creating, check whether a\n\t// `(name, slug)` row exists in some OTHER locale -- e.g. the admin\n\t// pre-created an Arabic translation, and now an `en` import wants the\n\t// canonical row. We need to mint the new row inside the existing row's\n\t// `translation_group` so per-locale lookups across the family work.\n\t// Without this, the mirror pass would later refuse to reconcile (it\n\t// sees pre-existing rows in a different group as a no-op) and pivots\n\t// would point at a group that has no row in the requested locale.\n\tconst anyLocale = await repo.findBySlug(taxonomyName, slug);\n\tconst translationOf = anyLocale?.id;\n\n\tconst created = await repo.create({\n\t\tname: taxonomyName,\n\t\tslug,\n\t\tlabel,\n\t\tdata: description ? { description } : undefined,\n\t\tlocale,\n\t\ttranslationOf,\n\t});\n\tbump(state.plan.termsCreated, taxonomyName);\n\trememberTerm(state, taxonomyName, slug, created.id);\n\treturn created.id;\n}\n\n/**\n * Retrieve the human label captured by the parser for a per-item\n * `<category>` text body, falling back to the slug when the parser didn't\n * see a label (e.g. self-closing tags or whitespace-only bodies).\n */\nfunction labelFor(post: WxrPost, taxonomy: string, slug: string): string {\n\tconst key = `${taxonomy}\\u0000${slug}`;\n\treturn post.taxonomyLabels?.get(key) ?? slug;\n}\n\n/**\n * Pre-import every term referenced by the WXR file.\n *\n * Pass 1: `wp:category` blocks. Each becomes a term in EmDash's seeded\n *         `category` taxonomy.\n * Pass 2: `wp:tag` blocks. Each becomes a term in `tag`.\n * Pass 3: `wp:term` blocks (custom taxonomies). Skipped when no matching\n *         EmDash def exists.\n * Pass 4: per-item `<category domain=\"…\" nicename=\"…\">` assignments. WXR\n *         exports sometimes reference taxonomies/terms that weren't declared\n *         at the top level (older exports especially), so we backfill terms\n *         from per-item assignments. Categories and tags use the seeded defs\n *         and pick up the assignment text as the label; custom domains fall\n *         back to the same \"def must exist\" rule.\n */\nexport async function preImportWxrTaxonomies(\n\tdb: Kysely<Database>,\n\tposts: WxrPost[],\n\tcategories: WxrCategory[],\n\ttags: WxrTag[],\n\tterms: WxrTerm[],\n\tlocale: string | undefined,\n): Promise<TaxonomyImportPlan> {\n\tconst state = makeState();\n\tconst repo = new TaxonomyRepository(db);\n\n\t// Cache def lookups for the duration of the import. Keyed by name; value\n\t// is `null` when we've already determined the def is missing in this\n\t// locale (so we only report the \"missing\" warning once per taxonomy).\n\tconst defCache = new Map<string, { id: string; collections: string[] } | null>();\n\tconst lookupDef = async (name: string): Promise<{ id: string; collections: string[] } | null> => {\n\t\tif (defCache.has(name)) return defCache.get(name) ?? null;\n\t\tconst def = await findTaxonomyDef(db, name, locale);\n\t\tdefCache.set(name, def);\n\t\tif (def) {\n\t\t\tstate.plan.collectionsByTaxonomy.set(name, new Set(def.collections));\n\t\t}\n\t\treturn def;\n\t};\n\n\t// Pass 1: top-level <wp:category> blocks -> EmDash `category` taxonomy.\n\tconst categoryDef = await lookupDef(\"category\");\n\tif (categoryDef) {\n\t\tfor (const cat of categories) {\n\t\t\tconst slug = cat.nicename;\n\t\t\tconst label = cat.name;\n\t\t\tif (!slug || !label) continue;\n\t\t\tawait ensureTerm(repo, state, \"category\", slug, label, cat.description, locale);\n\t\t}\n\t} else if (categories.length > 0) {\n\t\t// Seeded `category` def was deleted by the user — record so the\n\t\t// import response can surface why none of the categories landed.\n\t\tstate.plan.missingTaxonomies.push(\"category\");\n\t}\n\n\t// Pass 2: top-level <wp:tag> blocks -> EmDash `tag` taxonomy.\n\tconst tagDef = await lookupDef(\"tag\");\n\tif (tagDef) {\n\t\tfor (const tag of tags) {\n\t\t\tconst slug = tag.slug;\n\t\t\tconst label = tag.name;\n\t\t\tif (!slug || !label) continue;\n\t\t\tawait ensureTerm(repo, state, \"tag\", slug, label, tag.description, locale);\n\t\t}\n\t} else if (tags.length > 0) {\n\t\tstate.plan.missingTaxonomies.push(\"tag\");\n\t}\n\n\t// Pass 3: <wp:term> blocks for custom taxonomies (genre, etc.). Skipped:\n\t//   - `nav_menu`: menus are handled by `importMenusFromWxr`.\n\t//   - `language`: Polylang's locale signal; promoted to `WxrPost.locale`\n\t//     by the parser and not a content taxonomy in EmDash.\n\tfor (const term of terms) {\n\t\tif (term.taxonomy === \"nav_menu\" || term.taxonomy === \"language\") continue;\n\t\t// Normalize WordPress' `post_tag` synonym -> EmDash `tag`. WordPress\n\t\t// emits `<wp:tag>` for some exports and `<wp:term wp:term_taxonomy=\"post_tag\">`\n\t\t// for others; both must land in the same EmDash taxonomy.\n\t\tconst taxonomyName = term.taxonomy === \"post_tag\" ? \"tag\" : term.taxonomy;\n\t\tconst def = await lookupDef(taxonomyName);\n\t\tif (!def) {\n\t\t\tif (!state.plan.missingTaxonomies.includes(taxonomyName)) {\n\t\t\t\tstate.plan.missingTaxonomies.push(taxonomyName);\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tawait ensureTerm(repo, state, taxonomyName, term.slug, term.name, term.description, locale);\n\t}\n\n\t// Pass 4: per-item assignments. Backfills terms missing from the top-\n\t// level blocks (rare, but observed in hand-edited or partial exports).\n\t// Labels come from the per-item `<category>` text body when the parser\n\t// captured one; otherwise we fall back to the slug. This is the path\n\t// for older exports that skip top-level `<wp:category>` definitions.\n\tlet recordedMissingCategoryFromPosts = false;\n\tlet recordedMissingTagFromPosts = false;\n\tfor (const post of posts) {\n\t\tfor (const slug of post.categories) {\n\t\t\tif (!categoryDef) {\n\t\t\t\tif (\n\t\t\t\t\t!recordedMissingCategoryFromPosts &&\n\t\t\t\t\t!state.plan.missingTaxonomies.includes(\"category\")\n\t\t\t\t) {\n\t\t\t\t\tstate.plan.missingTaxonomies.push(\"category\");\n\t\t\t\t\trecordedMissingCategoryFromPosts = true;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (state.plan.termIdByNameAndSlug.get(\"category\")?.has(slug)) continue;\n\t\t\tawait ensureTerm(\n\t\t\t\trepo,\n\t\t\t\tstate,\n\t\t\t\t\"category\",\n\t\t\t\tslug,\n\t\t\t\tlabelFor(post, \"category\", slug),\n\t\t\t\tundefined,\n\t\t\t\tlocale,\n\t\t\t);\n\t\t}\n\t\tfor (const slug of post.tags) {\n\t\t\tif (!tagDef) {\n\t\t\t\tif (!recordedMissingTagFromPosts && !state.plan.missingTaxonomies.includes(\"tag\")) {\n\t\t\t\t\tstate.plan.missingTaxonomies.push(\"tag\");\n\t\t\t\t\trecordedMissingTagFromPosts = true;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (state.plan.termIdByNameAndSlug.get(\"tag\")?.has(slug)) continue;\n\t\t\tawait ensureTerm(repo, state, \"tag\", slug, labelFor(post, \"tag\", slug), undefined, locale);\n\t\t}\n\t\tif (post.customTaxonomies) {\n\t\t\tfor (const [rawName, slugs] of post.customTaxonomies) {\n\t\t\t\t// `nav_menu` is handled by the menu importer; `language` is\n\t\t\t\t// Polylang's per-post locale signal, already promoted by the\n\t\t\t\t// parser.\n\t\t\t\tif (rawName === \"nav_menu\" || rawName === \"language\") continue;\n\t\t\t\tconst taxonomyName = rawName === \"post_tag\" ? \"tag\" : rawName;\n\t\t\t\tconst def = await lookupDef(taxonomyName);\n\t\t\t\tif (!def) {\n\t\t\t\t\tif (!state.plan.missingTaxonomies.includes(taxonomyName)) {\n\t\t\t\t\t\tstate.plan.missingTaxonomies.push(taxonomyName);\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tfor (const slug of slugs) {\n\t\t\t\t\tif (state.plan.termIdByNameAndSlug.get(taxonomyName)?.has(slug)) continue;\n\t\t\t\t\tawait ensureTerm(\n\t\t\t\t\t\trepo,\n\t\t\t\t\t\tstate,\n\t\t\t\t\t\ttaxonomyName,\n\t\t\t\t\t\tslug,\n\t\t\t\t\t\tlabelFor(post, taxonomyName, slug),\n\t\t\t\t\t\tundefined,\n\t\t\t\t\t\tlocale,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// `content_taxonomies` writes happen later in `attachPostTaxonomies`, but\n\t// term inserts above already invalidate the in-memory \"has any terms\" probe.\n\t// We flush once at the end of the pre-import to keep the runtime cache hot.\n\tinvalidateTermCache();\n\n\treturn state.plan;\n}\n\n/**\n * Walk a parsed WXR post's per-item taxonomy assignments and return only\n * the ones that resolve to a real EmDash term AND aren't filtered out by\n * the taxonomy def's `collections` allowlist. Grouped by EmDash taxonomy\n * name (so `post_tag` is already folded into `tag`). Deduplicated.\n *\n * This is the single source of truth for \"what will the importer try to\n * write for this post\". Both the anchor (additive `attachToEntry`) and\n * translation (per-taxonomy `setTermsForEntry`) paths drive from this map\n * so they agree on which taxonomies need touching. In particular, the\n * translation path uses the keys here -- not `postAssignedTaxonomies` --\n * to decide which inherited pivot rows to clear, so a translation whose\n * only assignment is filtered out by `collections` doesn't lose its\n * inherited terms (see #1087 review feedback).\n *\n * Skipped taxonomies: `nav_menu` (handled by the menu importer) and\n * `language` (Polylang's locale signal, already promoted to `post.locale`\n * by the parser).\n */\nexport function resolvePostTermAssignments(\n\tcollection: string,\n\tpost: WxrPost,\n\tplan: TaxonomyImportPlan,\n): Map<string, string[]> {\n\tconst result = new Map<string, string[]>();\n\tconst seen = new Set<string>();\n\n\tconst tryResolve = (taxonomyName: string, slug: string): void => {\n\t\tconst termId = plan.termIdByNameAndSlug.get(taxonomyName)?.get(slug);\n\t\tif (!termId) return;\n\t\tconst collectionFilter = plan.collectionsByTaxonomy.get(taxonomyName);\n\t\t// Empty set means \"no filter\" (def has no collections array). A\n\t\t// non-empty set is enforced: skip assignments to collections the\n\t\t// def doesn't list. Matches admin UI: a `category` term linked\n\t\t// only to `posts` shouldn't end up on a `products` row just\n\t\t// because the WXR happened to mention it.\n\t\tif (collectionFilter && collectionFilter.size > 0 && !collectionFilter.has(collection)) {\n\t\t\treturn;\n\t\t}\n\t\tconst dedupeKey = `${taxonomyName}\\u0000${termId}`;\n\t\tif (seen.has(dedupeKey)) return;\n\t\tseen.add(dedupeKey);\n\t\tconst existing = result.get(taxonomyName);\n\t\tif (existing) existing.push(termId);\n\t\telse result.set(taxonomyName, [termId]);\n\t};\n\n\tfor (const slug of post.categories) tryResolve(\"category\", slug);\n\tfor (const slug of post.tags) tryResolve(\"tag\", slug);\n\tif (post.customTaxonomies) {\n\t\tfor (const [rawName, slugs] of post.customTaxonomies) {\n\t\t\tif (rawName === \"nav_menu\" || rawName === \"language\") continue;\n\t\t\tconst taxonomyName = rawName === \"post_tag\" ? \"tag\" : rawName;\n\t\t\tfor (const slug of slugs) tryResolve(taxonomyName, slug);\n\t\t}\n\t}\n\n\treturn result;\n}\n\n/**\n * Attach the taxonomy assignments parsed for a single WXR post to a freshly-\n * created EmDash content row. Additive (`attachToEntry` + `ON CONFLICT DO\n * NOTHING`). Used for anchors -- translations need replace-semantics per\n * taxonomy and should use `setPostTermAssignmentsReplacing` instead.\n *\n * Returns the number of pivot rows actually inserted (excludes rows that\n * already existed via the `ON CONFLICT DO NOTHING` path), so the caller can\n * roll them up into the import summary without over-counting on re-imports.\n */\nexport async function attachPostTaxonomies(\n\tdb: Kysely<Database>,\n\tcollection: string,\n\tentryId: string,\n\tpost: WxrPost,\n\tplan: TaxonomyImportPlan,\n): Promise<number> {\n\tconst repo = new TaxonomyRepository(db);\n\tconst resolved = resolvePostTermAssignments(collection, post, plan);\n\tconst groups = new Set<string>();\n\tfor (const [, termIds] of resolved) {\n\t\tfor (const termId of termIds) {\n\t\t\tconst group = await termTranslationGroup(repo, plan, termId);\n\t\t\tif (group) groups.add(group);\n\t\t}\n\t}\n\treturn repo.attachGroupsToEntry(collection, entryId, [...groups]);\n}\n\n/**\n * Replace assignments per-taxonomy from a parsed WXR post. Used for\n * translations. Assignments belong to the content translation_group, so a\n * translated item's explicit taxonomy replaces that taxonomy for every\n * locale. Taxonomies with no resolvable permitted terms are left unchanged.\n *\n * Returns the number of pivot rows after replacement (sum of `termIds`\n * lists across taxonomies actually touched). Note this counts logical\n * assignments, not the delta from the prior state; the import summary\n * treats this as an additive count for compatibility with `attachPost-\n * Taxonomies`.\n */\nexport async function setPostTermAssignmentsReplacing(\n\tdb: Kysely<Database>,\n\tcollection: string,\n\tentryId: string,\n\tpost: WxrPost,\n\tplan: TaxonomyImportPlan,\n): Promise<number> {\n\tconst repo = new TaxonomyRepository(db);\n\tconst resolved = resolvePostTermAssignments(collection, post, plan);\n\n\tlet attached = 0;\n\tfor (const [taxonomyName, termIds] of resolved) {\n\t\tawait repo.setTermsForEntry(collection, entryId, taxonomyName, termIds);\n\t\tattached += termIds.length;\n\t}\n\treturn attached;\n}\n\n/**\n * Resolve a term id to its `translation_group` (the value\n * `content_taxonomies` stores). Caches the result on the plan so\n * repeated attaches of the same term don't repeat the lookup.\n */\nasync function termTranslationGroup(\n\trepo: TaxonomyRepository,\n\tplan: TaxonomyImportPlan,\n\ttermId: string,\n): Promise<string | null> {\n\tconst cached = plan.translationGroupByTermId.get(termId);\n\tif (cached !== undefined) return cached;\n\tconst term = await repo.findById(termId);\n\tconst group = term?.translationGroup ?? null;\n\tplan.translationGroupByTermId.set(termId, group);\n\treturn group;\n}\n\n/**\n * Mirror every term in the plan into each additional locale used by the\n * incoming posts. New rows share the canonical term's `translation_group`\n * so per-locale lookups (`getTermsForEntry(..., locale)`) resolve correctly\n * for translations whose locale differs from the import-wide one.\n *\n * Without this pass, multilingual WXR imports (#1080) write all term rows\n * at the upload-wide locale; the `content_taxonomies` pivot is correct (it\n * stores `translation_group`, not `term id`), but\n * `getTermsForEntry(collection, arabicPostId, \"category\", \"ar\")` filters on\n * `taxonomies.locale = \"ar\"` and returns zero rows. Users see \"no tags\" on\n * every non-canonical translation.\n *\n * Idempotent: skips a locale when a row already exists at `(name, slug,\n * locale)`. Safe to call after `preImportWxrTaxonomies` on subsequent\n * imports.\n */\nexport async function mirrorTermsToLocales(\n\tdb: Kysely<Database>,\n\tplan: TaxonomyImportPlan,\n\tpostLocales: Iterable<string>,\n\tcanonicalLocale: string | undefined,\n): Promise<void> {\n\tconst localeSet = new Set<string>();\n\tfor (const locale of postLocales) {\n\t\tif (!locale || locale === canonicalLocale) continue;\n\t\tlocaleSet.add(locale);\n\t}\n\tif (localeSet.size === 0) return;\n\n\tconst repo = new TaxonomyRepository(db);\n\n\tfor (const [taxonomyName, bySlug] of plan.termIdByNameAndSlug) {\n\t\tfor (const [slug, canonicalTermId] of bySlug) {\n\t\t\t// Resolve the canonical's translation_group once; we'll compare\n\t\t\t// against any pre-existing rows we find at the target locales.\n\t\t\t// Cache on the plan so subsequent attaches (which also need\n\t\t\t// this resolution) don't repeat the lookup.\n\t\t\tconst cachedGroup = await termTranslationGroup(repo, plan, canonicalTermId);\n\t\t\tif (!cachedGroup) {\n\t\t\t\t// The canonical term id is in the plan but the row is no\n\t\t\t\t// longer in the DB. Shouldn't happen during a single\n\t\t\t\t// import run; skip rather than crash so the rest of the\n\t\t\t\t// import can complete.\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst canonicalGroup = cachedGroup;\n\n\t\t\tfor (const locale of localeSet) {\n\t\t\t\tconst existing = await repo.findBySlug(taxonomyName, slug, locale);\n\t\t\t\tif (existing) {\n\t\t\t\t\t// `ensureTerm` resolves cross-locale grouping when it\n\t\t\t\t\t// creates the canonical row, so a pre-existing sibling\n\t\t\t\t\t// row at this locale should already share the\n\t\t\t\t\t// canonical's `translation_group`. If it doesn't, the\n\t\t\t\t\t// import would write pivots pointing at a group that\n\t\t\t\t\t// has no row in this locale -- a silent data-integrity\n\t\t\t\t\t// bug. Fail closed: throw so the operator reconciles\n\t\t\t\t\t// the existing rows in the admin before retrying. This\n\t\t\t\t\t// happens when the canonical row was created in an\n\t\t\t\t\t// earlier import and a sibling-locale row was added\n\t\t\t\t\t// manually afterwards (or vice versa) without linking\n\t\t\t\t\t// them via translationOf.\n\t\t\t\t\tif (existing.translationGroup !== canonicalGroup) {\n\t\t\t\t\t\tthrow new WxrTaxonomyConflictError(\n\t\t\t\t\t\t\t`Cannot import: term \"${taxonomyName}/${slug}\" already exists at locale \"${locale}\" in a different translation group than the canonical row at this import's locale. Reconcile the rows in the admin (re-link via translationOf, or delete one) and retry.`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tawait repo.create({\n\t\t\t\t\t\tname: taxonomyName,\n\t\t\t\t\t\tslug,\n\t\t\t\t\t\tlabel: slug, // we don't have a per-locale label from the WXR\n\t\t\t\t\t\tlocale,\n\t\t\t\t\t\ttranslationOf: canonicalTermId,\n\t\t\t\t\t});\n\t\t\t\t} catch (error) {\n\t\t\t\t\t// `findBySlug` + `create` is not atomic. A concurrent\n\t\t\t\t\t// import racing us into the same `(name, slug, locale)`\n\t\t\t\t\t// will trip the UNIQUE constraint. Re-read the row that\n\t\t\t\t\t// won the race and verify its `translation_group`\n\t\t\t\t\t// matches the canonical's; if not, the pivot will\n\t\t\t\t\t// resolve to a group that has no row in this locale\n\t\t\t\t\t// (silent data-integrity bug) so we surface that loudly\n\t\t\t\t\t// rather than continue.\n\t\t\t\t\t//\n\t\t\t\t\t// Other errors (validation, connectivity) re-throw so\n\t\t\t\t\t// the import fails closed rather than silently shipping\n\t\t\t\t\t// translations that resolve to empty taxonomy queries.\n\t\t\t\t\tconst message = error instanceof Error ? error.message.toLowerCase() : \"\";\n\t\t\t\t\tconst isUniqueRace =\n\t\t\t\t\t\tmessage.includes(\"unique constraint failed\") || message.includes(\"duplicate key\");\n\t\t\t\t\tif (!isUniqueRace) throw error;\n\n\t\t\t\t\tconst winner = await repo.findBySlug(taxonomyName, slug, locale);\n\t\t\t\t\tif (!winner) {\n\t\t\t\t\t\t// UNIQUE conflict but no row visible? Shouldn't\n\t\t\t\t\t\t// happen unless the racing transaction rolled back;\n\t\t\t\t\t\t// fail loudly so the operator can investigate.\n\t\t\t\t\t\tthrow new WxrTaxonomyConflictError(\n\t\t\t\t\t\t\t`Cannot import: term \"${taxonomyName}/${slug}\" raced UNIQUE at locale \"${locale}\" but no row is visible afterwards. The concurrent transaction may have rolled back; retry the import.`,\n\t\t\t\t\t\t\t{ cause: error },\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tif (winner.translationGroup !== canonicalGroup) {\n\t\t\t\t\t\tthrow new WxrTaxonomyConflictError(\n\t\t\t\t\t\t\t`Cannot import: term \"${taxonomyName}/${slug}\" raced UNIQUE at locale \"${locale}\" with a different translation group. Reconcile the rows in the admin and retry.`,\n\t\t\t\t\t\t\t{ cause: error },\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t`[WXR import] concurrent writer beat us to term \"${taxonomyName}/${slug}\" at locale \"${locale}\"; using existing row (same group).`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n"],"mappings":";;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