emdash 0.28.0 → 0.28.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/route-utils.mjs +2 -2
- package/dist/api/schemas/index.d.mts +1 -1
- package/dist/{api-BFURZn1i.mjs → api-DxFSorgk.mjs} +2 -2
- package/dist/{api-BFURZn1i.mjs.map → api-DxFSorgk.mjs.map} +1 -1
- package/dist/{apply-Bu-8nYHL.mjs → apply-CDJqIjPU.mjs} +8 -8
- package/dist/{apply-Bu-8nYHL.mjs.map → apply-CDJqIjPU.mjs.map} +1 -1
- package/dist/astro/index.d.mts +1 -1
- package/dist/astro/index.mjs +1 -1
- package/dist/astro/middleware/auth.d.mts +1 -1
- package/dist/astro/middleware.mjs +15 -15
- package/dist/astro/routes/api/admin/bylines/_id_/index.mjs +1 -1
- package/dist/astro/routes/api/admin/bylines/_id_/translations.mjs +1 -1
- package/dist/astro/routes/api/admin/bylines/index.mjs +1 -1
- package/dist/astro/routes/api/admin/plugins/_id_/disable.mjs +6 -6
- package/dist/astro/routes/api/admin/plugins/_id_/enable.mjs +6 -6
- package/dist/astro/routes/api/admin/plugins/_id_/index.mjs +6 -6
- package/dist/astro/routes/api/admin/plugins/_id_/uninstall.mjs +6 -6
- package/dist/astro/routes/api/admin/plugins/_id_/update.mjs +6 -6
- package/dist/astro/routes/api/admin/plugins/index.mjs +6 -6
- package/dist/astro/routes/api/admin/plugins/marketplace/_id_/index.mjs +6 -6
- package/dist/astro/routes/api/admin/plugins/marketplace/_id_/install.mjs +6 -6
- package/dist/astro/routes/api/admin/plugins/marketplace/index.mjs +6 -6
- package/dist/astro/routes/api/admin/plugins/registry/_id_/uninstall.mjs +6 -6
- package/dist/astro/routes/api/admin/plugins/registry/_id_/update.mjs +7 -7
- package/dist/astro/routes/api/admin/plugins/registry/artifact.mjs +6 -6
- package/dist/astro/routes/api/admin/plugins/registry/install.mjs +7 -7
- package/dist/astro/routes/api/admin/plugins/updates.mjs +6 -6
- package/dist/astro/routes/api/admin/themes/marketplace/_id_/index.mjs +6 -6
- package/dist/astro/routes/api/admin/themes/marketplace/index.mjs +6 -6
- package/dist/astro/routes/api/content/_collection_/_id_/terms/_taxonomy_.mjs +1 -1
- package/dist/astro/routes/api/import/wordpress/execute.d.mts +1 -1
- package/dist/astro/routes/api/import/wordpress/execute.mjs +2 -2
- package/dist/astro/routes/api/import/wordpress/media.d.mts +1 -1
- package/dist/astro/routes/api/import/wordpress/prepare.mjs +1 -1
- package/dist/astro/routes/api/import/wordpress/rewrite-urls.d.mts +1 -1
- package/dist/astro/routes/api/import/wordpress/rewrite-urls.mjs +2 -2
- package/dist/astro/routes/api/import/wordpress-plugin/execute.d.mts +1 -1
- package/dist/astro/routes/api/import/wordpress-plugin/execute.mjs +3 -3
- package/dist/astro/routes/api/manifest.mjs +1 -1
- package/dist/astro/routes/api/mcp.mjs +14 -14
- package/dist/astro/routes/api/plugins/_pluginId_/_...path_.d.mts.map +1 -1
- package/dist/astro/routes/api/plugins/_pluginId_/_...path_.mjs +2 -10
- package/dist/astro/routes/api/plugins/_pluginId_/_...path_.mjs.map +1 -1
- package/dist/astro/routes/api/schema/collections/_slug_/fields/_fieldSlug_.mjs +6 -6
- package/dist/astro/routes/api/schema/collections/_slug_/fields/index.mjs +6 -6
- package/dist/astro/routes/api/schema/collections/_slug_/fields/reorder.mjs +6 -6
- package/dist/astro/routes/api/schema/collections/_slug_/index.mjs +6 -6
- package/dist/astro/routes/api/schema/collections/index.mjs +6 -6
- package/dist/astro/routes/api/schema/index.mjs +2 -2
- package/dist/astro/routes/api/schema/orphans/_slug_.mjs +6 -6
- package/dist/astro/routes/api/schema/orphans/index.mjs +6 -6
- package/dist/astro/routes/api/setup/dev-bypass.mjs +3 -3
- package/dist/astro/routes/api/setup/index.mjs +3 -3
- package/dist/astro/routes/api/taxonomies/_name_/terms/_slug_/translations.mjs +2 -2
- package/dist/astro/routes/api/taxonomies/_name_/terms/_slug_.mjs +2 -2
- package/dist/astro/routes/api/taxonomies/_name_/terms/index.mjs +2 -2
- package/dist/astro/routes/api/taxonomies/index.mjs +2 -2
- package/dist/astro/routes/api/typegen.mjs +2 -2
- package/dist/astro/types.d.mts +1 -1
- package/dist/{byline-fields-Cgrt9-aL.d.mts → byline-fields-CHE8UStY.d.mts} +3 -3
- package/dist/{byline-fields-Cgrt9-aL.d.mts.map → byline-fields-CHE8UStY.d.mts.map} +1 -1
- package/dist/{bylines-Woq87129.mjs → bylines-CAZxGSrm.mjs} +2 -2
- package/dist/{bylines-Woq87129.mjs.map → bylines-CAZxGSrm.mjs.map} +1 -1
- package/dist/cli/index.mjs +3 -3
- package/dist/{content-refresh-CA4uKwzH.mjs → content-refresh-Br4gMzh8.mjs} +13 -7
- package/dist/content-refresh-Br4gMzh8.mjs.map +1 -0
- package/dist/{context-CUsR9dXL.mjs → context-BRIpHARC.mjs} +2 -2
- package/dist/{context-CUsR9dXL.mjs.map → context-BRIpHARC.mjs.map} +1 -1
- package/dist/index.d.mts +1 -1
- package/dist/index.mjs +11 -11
- package/dist/media/local-runtime.d.mts +1 -1
- package/dist/{menus-CsZ2ZEK2.mjs → menus-b2T4clbO.mjs} +2 -2
- package/dist/{menus-CsZ2ZEK2.mjs.map → menus-b2T4clbO.mjs.map} +1 -1
- package/dist/plugin-utils.d.mts +1 -1
- package/dist/plugins/adapt-sandbox-entry.d.mts +1 -1
- package/dist/{query-ByGq6ver.mjs → query-1Cp6U9oo.mjs} +5 -5
- package/dist/{query-ByGq6ver.mjs.map → query-1Cp6U9oo.mjs.map} +1 -1
- package/dist/{registry-B65mUtPa.mjs → registry-B57vp_X9.mjs} +2 -2
- package/dist/{registry-B65mUtPa.mjs.map → registry-B57vp_X9.mjs.map} +1 -1
- package/dist/runtime.d.mts +1 -1
- package/dist/{schema-Blhoxp3P.mjs → schema-CX9cfNkZ.mjs} +2 -2
- package/dist/{schema-Blhoxp3P.mjs.map → schema-CX9cfNkZ.mjs.map} +1 -1
- package/dist/seed/index.mjs +3 -3
- package/dist/{taxonomies-BGBd16Eu.mjs → taxonomies-Bs13SN-F.mjs} +2 -2
- package/dist/{taxonomies-BGBd16Eu.mjs.map → taxonomies-Bs13SN-F.mjs.map} +1 -1
- package/dist/{taxonomies-Cnb4F-Pb.mjs → taxonomies-kH9ABDUF.mjs} +2 -2
- package/dist/{taxonomies-Cnb4F-Pb.mjs.map → taxonomies-kH9ABDUF.mjs.map} +1 -1
- package/dist/{validation-c8WjhH8z.mjs → validation-0l8-RYj4.mjs} +3 -3
- package/dist/{validation-c8WjhH8z.mjs.map → validation-0l8-RYj4.mjs.map} +1 -1
- package/dist/version-qmeO1XZY.mjs +7 -0
- package/dist/{version-CaccU7DM.mjs.map → version-qmeO1XZY.mjs.map} +1 -1
- package/dist/{wxr-taxonomies-BC3OYpvx.mjs → wxr-taxonomies-CNFcsNCr.mjs} +2 -2
- package/dist/{wxr-taxonomies-BC3OYpvx.mjs.map → wxr-taxonomies-CNFcsNCr.mjs.map} +1 -1
- package/package.json +5 -5
- package/src/astro/routes/api/plugins/[pluginId]/[...path].ts +17 -15
- package/src/database/repositories/media-usage.ts +25 -3
- package/src/media/usage/content-repair.ts +206 -22
- package/src/media/usage/content-snapshots.ts +4 -0
- package/dist/content-refresh-CA4uKwzH.mjs.map +0 -1
- package/dist/version-CaccU7DM.mjs +0 -7
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"taxonomies-Cnb4F-Pb.mjs","names":[],"sources":["../src/taxonomies/index.ts"],"sourcesContent":["/**\n * Runtime API for taxonomies.\n *\n * All helpers are locale-aware. When a locale is not passed explicitly we fall\n * back to the request context or the configured `defaultLocale` (see\n * `i18n/resolve.ts`).\n *\n * Because `content_taxonomies.taxonomy_id` stores the translation_group (not a\n * specific term id), the joins here are `taxonomies.translation_group =\n * content_taxonomies.taxonomy_id` + filter by `taxonomies.locale`, which picks\n * the right per-locale term.\n */\n\nimport { resolveLocale, resolveLocaleChain } from \"../i18n/resolve.js\";\nimport { getDb, resetTaxonomyNamesCache } from \"../loader.js\";\nimport {\n\tcachedQuery,\n\tCacheNamespace,\n\tcontentNamespace,\n\tinvalidateTaxonomyObjectCache,\n\tisObjectCacheActive,\n} from \"../object-cache/index.js\";\nimport { peekRequestCache, requestCached, setRequestCacheEntry } from \"../request-cache.js\";\nimport { getRequestContext } from \"../request-context.js\";\nimport { chunks, SQL_BATCH_SIZE } from \"../utils/chunks.js\";\nimport { isMissingTableError } from \"../utils/db-errors.js\";\nimport type { TaxonomyDef, TaxonomyTerm, TaxonomyTermRow } from \"./types.js\";\n\nexport interface TaxonomyQueryOptions {\n\tlocale?: string;\n}\n\n/** Invalidate cached taxonomy term data and any content that hydrates terms. */\nexport function invalidateTermCache(): void {\n\tinvalidateTaxonomyObjectCache();\n}\n\n/**\n * Worker-isolate cache for taxonomy definitions, keyed by resolved locale.\n *\n * Taxonomy *definitions* (the \"category\"/\"tag\" taxonomies themselves, not\n * their terms) are read on every public render that hydrates entry terms —\n * `getAllTermsForEntries` → `getCollectionTaxonomyNames` → `getTaxonomyDefs` —\n * but change extremely rarely: they're created via the admin API or applied\n * from a seed, and there is no edit/delete-def path. Caching them across the\n * isolate lifetime drops the per-render `SELECT * FROM _emdash_taxonomy_defs`\n * to once-per-isolate.\n *\n * Stored on globalThis behind a Symbol key (same pattern as\n * `settings/index.ts`) so the bundler duplicating this module across SSR\n * chunks can't produce two independent caches.\n *\n * When the distributed object cache is configured, it is authoritative and this\n * fallback is bypassed so cross-isolate epoch invalidation cannot be undercut\n * by stale per-isolate data on an object-cache miss.\n *\n * **Isolated databases bypass the cache.** Playground / DO preview requests\n * set `requestContext.dbIsIsolated`; they point at a divergent schema, so we\n * skip both reading and writing the global holder and fall back to the\n * per-request cache (same precedent as `getTaxonomyNames` / byline field defs).\n */\ninterface TaxonomyDefsHolder {\n\tversion: number;\n\t/** locale key (\"*\" for \"all locales\") → { version it was fetched at, promise }. */\n\tcache: Map<string, { version: number; promise: Promise<TaxonomyDef[]> }>;\n}\n\nconst TAXONOMY_DEFS_CACHE_KEY = Symbol.for(\"emdash:taxonomy-defs\");\nconst taxonomyDefsStore = globalThis as Record<symbol, unknown>;\nconst defsHolder: TaxonomyDefsHolder =\n\t// eslint-disable-next-line typescript/no-unsafe-type-assertion -- globalThis singleton pattern (see settings/index.ts)\n\t(taxonomyDefsStore[TAXONOMY_DEFS_CACHE_KEY] as TaxonomyDefsHolder | undefined) ??\n\t(() => {\n\t\tconst h: TaxonomyDefsHolder = { version: 0, cache: new Map() };\n\t\ttaxonomyDefsStore[TAXONOMY_DEFS_CACHE_KEY] = h;\n\t\treturn h;\n\t})();\n\n/**\n * Invalidate the isolate-wide taxonomy-definitions cache (and the related\n * loader taxonomy-names cache). Called from every taxonomy-def write path\n * (`handleTaxonomyCreate`, seed application). Other isolates refresh on their\n * next recycle — staleness bounded by isolate lifetime.\n */\nexport function invalidateTaxonomyDefsCache(): void {\n\tdefsHolder.version++;\n\tdefsHolder.cache.clear();\n\tresetTaxonomyNamesCache();\n\tinvalidateTaxonomyObjectCache();\n}\n\n/**\n * Test/internal helper: clear the per-isolate taxonomy-defs cache. Useful for\n * unit tests that insert defs directly and need to force a refetch without\n * going through a write path. Production code should rely on\n * `invalidateTaxonomyDefsCache()`.\n */\nexport function resetTaxonomyDefsCacheForTests(): void {\n\tdefsHolder.version++;\n\tdefsHolder.cache.clear();\n}\n\n/**\n * Fetch taxonomy definitions straight from the database (no caching).\n */\nasync function fetchTaxonomyDefs(locale: string | undefined): Promise<TaxonomyDef[]> {\n\tconst db = await getDb();\n\tlet query = db.selectFrom(\"_emdash_taxonomy_defs\").selectAll();\n\tif (locale !== undefined) query = query.where(\"locale\", \"=\", locale);\n\tconst rows = await query.execute();\n\treturn rows.map(rowToTaxonomyDef);\n}\n\n/**\n * Resolve taxonomy defs through the isolate fallback cache, bypassing it for\n * isolated databases. The returned promise is cached (not the resolved value)\n * so concurrent cold-isolate readers share one in-flight query; a rejection\n * evicts the entry so the next caller retries.\n */\nfunction loadTaxonomyDefs(localeKey: string, locale: string | undefined): Promise<TaxonomyDef[]> {\n\tif (getRequestContext()?.dbIsIsolated === true) {\n\t\treturn fetchTaxonomyDefs(locale);\n\t}\n\tconst existing = defsHolder.cache.get(localeKey);\n\tif (existing && existing.version === defsHolder.version) {\n\t\treturn existing.promise;\n\t}\n\tconst version = defsHolder.version;\n\tconst promise = fetchTaxonomyDefs(locale).catch((error: unknown) => {\n\t\tconst current = defsHolder.cache.get(localeKey);\n\t\tif (current && current.promise === promise) {\n\t\t\tdefsHolder.cache.delete(localeKey);\n\t\t}\n\t\tthrow error;\n\t});\n\tdefsHolder.cache.set(localeKey, { version, promise });\n\treturn promise;\n}\n\n/**\n * Get every taxonomy definition. Definitions are per-locale (one row per\n * locale inside the same translation_group) — by default we resolve to the\n * active locale.\n *\n * Two-tier cache: per-request via `requestCached` (so a single render that\n * hydrates terms for several collections pays at most one call), then\n * per-isolate via the global holder (so warm renders issue zero queries).\n * The `requestCached` key is unchanged so `getTaxonomyDef`'s peek still hits.\n */\nexport async function getTaxonomyDefs(options: TaxonomyQueryOptions = {}): Promise<TaxonomyDef[]> {\n\tconst locale = resolveLocale(options.locale);\n\tconst localeKey = locale ?? \"*\";\n\treturn requestCached(`taxonomy-defs:${localeKey}`, async () => {\n\t\tif (await isObjectCacheActive()) {\n\t\t\treturn cachedQuery({\n\t\t\t\tnamespace: CacheNamespace.TAXONOMIES,\n\t\t\t\tkey: `defs:${localeKey}`,\n\t\t\t\tload: () => fetchTaxonomyDefs(locale),\n\t\t\t});\n\t\t}\n\t\treturn loadTaxonomyDefs(localeKey, locale);\n\t});\n}\n\n/**\n * Get a single taxonomy definition by name. Uses the fallback chain so even\n * if there is no translation for the active locale we still return something.\n *\n * If `getTaxonomyDefs()` has already loaded the full list in this request\n * (which happens during entry-term hydration on every page that renders a\n * collection), search the matching def in memory rather than running a\n * second query against `_emdash_taxonomy_defs`.\n */\nexport async function getTaxonomyDef(\n\tname: string,\n\toptions: TaxonomyQueryOptions = {},\n): Promise<TaxonomyDef | null> {\n\tconst chain = resolveLocaleChain(options.locale);\n\tconst peekKey = `taxonomy-defs:${resolveLocale(options.locale) ?? \"*\"}`;\n\tconst allDefs = peekRequestCache<TaxonomyDef[]>(peekKey);\n\tif (allDefs) {\n\t\tconst defs = await allDefs;\n\t\tif (chain.length === 0) return defs.find((d) => d.name === name) ?? null;\n\t\tfor (const locale of chain) {\n\t\t\tconst found = defs.find((d) => d.name === name && d.locale === locale);\n\t\t\tif (found) return found;\n\t\t}\n\t\treturn null;\n\t}\n\n\treturn requestCached(`taxonomy-def:${name}:${chain.join(\",\")}`, async () => {\n\t\tconst db = await getDb();\n\n\t\tif (chain.length === 0) {\n\t\t\tconst row = await db\n\t\t\t\t.selectFrom(\"_emdash_taxonomy_defs\")\n\t\t\t\t.selectAll()\n\t\t\t\t.where(\"name\", \"=\", name)\n\t\t\t\t.orderBy(\"locale\", \"asc\")\n\t\t\t\t.executeTakeFirst();\n\t\t\treturn row ? rowToTaxonomyDef(row) : null;\n\t\t}\n\n\t\tfor (const locale of chain) {\n\t\t\tconst row = await db\n\t\t\t\t.selectFrom(\"_emdash_taxonomy_defs\")\n\t\t\t\t.selectAll()\n\t\t\t\t.where(\"name\", \"=\", name)\n\t\t\t\t.where(\"locale\", \"=\", locale)\n\t\t\t\t.executeTakeFirst();\n\t\t\tif (row) return rowToTaxonomyDef(row);\n\t\t}\n\t\treturn null;\n\t});\n}\n\n/**\n * All terms of a taxonomy in a specific locale (flat for non-hierarchical,\n * tree for hierarchical).\n */\nexport async function getTaxonomyTerms(\n\ttaxonomyName: string,\n\toptions: TaxonomyQueryOptions = {},\n): Promise<TaxonomyTerm[]> {\n\tconst locale = resolveLocale(options.locale);\n\treturn requestCached(`taxonomy-terms:${taxonomyName}:${locale ?? \"*\"}`, () =>\n\t\tcachedQuery({\n\t\t\tnamespace: CacheNamespace.TAXONOMIES,\n\t\t\tkey: `terms:${taxonomyName}:${locale ?? \"*\"}`,\n\t\t\tload: () => loadTaxonomyTerms(taxonomyName, locale, options),\n\t\t}),\n\t);\n}\n\nasync function loadTaxonomyTerms(\n\ttaxonomyName: string,\n\tlocale: string | undefined,\n\toptions: TaxonomyQueryOptions,\n): Promise<TaxonomyTerm[]> {\n\tconst db = await getDb();\n\n\tconst def = await getTaxonomyDef(taxonomyName, options);\n\tif (!def) return [];\n\n\tlet termsQuery = db\n\t\t.selectFrom(\"taxonomies\")\n\t\t.selectAll()\n\t\t.where(\"name\", \"=\", taxonomyName)\n\t\t.orderBy(\"label\", \"asc\");\n\tif (locale !== undefined) termsQuery = termsQuery.where(\"locale\", \"=\", locale);\n\tconst rows = await termsQuery.execute();\n\n\t// Counts are keyed by translation_group (what the pivot stores) and are\n\t// locale-independent, so the aggregate is shared across every taxonomy\n\t// rendered in this request (Categories + Tags widgets, etc.).\n\tconst counts = await getTaxonomyTermCounts();\n\n\tconst flatTerms: TaxonomyTermRow[] = rows.map((row) => ({\n\t\tid: row.id,\n\t\tname: row.name,\n\t\tslug: row.slug,\n\t\tlabel: row.label,\n\t\tparent_id: row.parent_id,\n\t\tdata: row.data,\n\t\tlocale: row.locale,\n\t\ttranslation_group: row.translation_group,\n\t}));\n\n\tif (def.hierarchical) return buildTree(flatTerms, counts);\n\n\treturn flatTerms.map((term) => ({\n\t\tid: term.id,\n\t\tname: term.name,\n\t\tslug: term.slug,\n\t\tlabel: term.label,\n\t\tdescription: term.data ? JSON.parse(term.data).description : undefined,\n\t\tchildren: [],\n\t\tcount: counts.get(term.translation_group ?? term.id) ?? 0,\n\t\tlocale: term.locale,\n\t\ttranslationGroup: term.translation_group,\n\t}));\n}\n\n/**\n * Per-translation-group usage counts across all taxonomies, in one aggregate\n * scan of `content_taxonomies`. Counts are locale-independent (the pivot stores\n * translation_group), so a single request-cached entry serves every taxonomy\n * that renders during the request.\n */\nfunction getTaxonomyTermCounts(): Promise<Map<string, number>> {\n\treturn requestCached(\"taxonomy-term-counts\", async () => {\n\t\tconst db = await getDb();\n\t\tconst countsResult = await db\n\t\t\t.selectFrom(\"content_taxonomies\")\n\t\t\t.select([\"taxonomy_id\"])\n\t\t\t.select((eb) => eb.fn.count<number>(\"entry_id\").as(\"count\"))\n\t\t\t.groupBy(\"taxonomy_id\")\n\t\t\t.execute();\n\t\tconst counts = new Map<string, number>();\n\t\tfor (const row of countsResult) counts.set(row.taxonomy_id, row.count);\n\t\treturn counts;\n\t});\n}\n\n/**\n * Get a single term by (taxonomy, slug). Honours the fallback chain — if the\n * slug exists in a fallback locale, we return that row (useful for deep-linking\n * to a term page when the translation is missing).\n */\nexport async function getTerm(\n\ttaxonomyName: string,\n\tslug: string,\n\toptions: TaxonomyQueryOptions = {},\n): Promise<TaxonomyTerm | null> {\n\tconst chain = resolveLocaleChain(options.locale);\n\t// Cached under the shared taxonomies epoch (bumped on any taxonomy / term\n\t// assignment write). The `count` reflects content_taxonomies rows; a stale\n\t// count after a bare content delete is bounded by the entry's TTL.\n\treturn cachedQuery({\n\t\tnamespace: CacheNamespace.TAXONOMIES,\n\t\tkey: `term:${taxonomyName}:${slug}:${chain.join(\",\")}`,\n\t\tload: () => loadTerm(taxonomyName, slug, chain),\n\t});\n}\n\nasync function loadTerm(\n\ttaxonomyName: string,\n\tslug: string,\n\tchain: string[],\n): Promise<TaxonomyTerm | null> {\n\tconst db = await getDb();\n\n\tlet row: Awaited<ReturnType<ReturnType<typeof selectTerm>[\"executeTakeFirst\"]>>;\n\tconst selectTerm = () =>\n\t\tdb\n\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t.selectAll()\n\t\t\t.where(\"name\", \"=\", taxonomyName)\n\t\t\t.where(\"slug\", \"=\", slug);\n\n\tif (chain.length === 0) {\n\t\trow = await selectTerm().orderBy(\"locale\", \"asc\").executeTakeFirst();\n\t} else {\n\t\trow = undefined;\n\t\tfor (const locale of chain) {\n\t\t\trow = await selectTerm().where(\"locale\", \"=\", locale).executeTakeFirst();\n\t\t\tif (row) break;\n\t\t}\n\t}\n\n\tif (!row) return null;\n\n\tlet childrenQuery = db\n\t\t.selectFrom(\"taxonomies\")\n\t\t.selectAll()\n\t\t// Children store the parent's translation_group in parent_id (not a row\n\t\t// id), so a translated parent still owns its children in its own locale.\n\t\t.where(\"parent_id\", \"=\", row.translation_group ?? row.id)\n\t\t.orderBy(\"label\", \"asc\");\n\tconst termLocale = row.locale;\n\tif (termLocale) childrenQuery = childrenQuery.where(\"locale\", \"=\", termLocale);\n\n\t// The usage-count and children queries both depend only on the term row,\n\t// so run them concurrently to save a round trip on remote databases.\n\tconst [countResult, childRows] = await Promise.all([\n\t\tdb\n\t\t\t.selectFrom(\"content_taxonomies\")\n\t\t\t.select((eb) => eb.fn.count<number>(\"entry_id\").as(\"count\"))\n\t\t\t.where(\"taxonomy_id\", \"=\", row.translation_group ?? row.id)\n\t\t\t.executeTakeFirst(),\n\t\tchildrenQuery.execute(),\n\t]);\n\tconst count = countResult?.count ?? 0;\n\n\tconst children = childRows.map<TaxonomyTerm>((child) => ({\n\t\tid: child.id,\n\t\tname: child.name,\n\t\tslug: child.slug,\n\t\tlabel: child.label,\n\t\tparentId: child.parent_id ?? undefined,\n\t\tchildren: [],\n\t\tlocale: child.locale,\n\t\ttranslationGroup: child.translation_group,\n\t}));\n\n\treturn {\n\t\tid: row.id,\n\t\tname: row.name,\n\t\tslug: row.slug,\n\t\tlabel: row.label,\n\t\tparentId: row.parent_id ?? undefined,\n\t\tdescription: row.data ? JSON.parse(row.data).description : undefined,\n\t\tchildren,\n\t\tcount,\n\t\tlocale: row.locale,\n\t\ttranslationGroup: row.translation_group,\n\t};\n}\n\n/**\n * Terms assigned to a content entry, resolved into the active locale. Terms\n * whose translation_group lacks a row in the requested locale are omitted.\n */\nexport function getEntryTerms(\n\tcollection: string,\n\tentryId: string,\n\ttaxonomyName?: string,\n\toptions: TaxonomyQueryOptions = {},\n): Promise<TaxonomyTerm[]> {\n\tconst locale = resolveLocale(options.locale);\n\t// requestCached short-circuits to values primed by getAllTermsForEntries\n\t// during entry hydration (same key shape). On a warm content-cache hit\n\t// hydration doesn't run, so the inner cachedQuery serves this from KV\n\t// instead of falling through to D1 on every request.\n\treturn requestCached(\n\t\t`terms:${collection}:${entryId}:${taxonomyName ?? \"*\"}:${locale ?? \"*\"}`,\n\t\t() =>\n\t\t\tcachedQuery({\n\t\t\t\tnamespace: [contentNamespace(collection), CacheNamespace.TAXONOMIES],\n\t\t\t\tkey: `entryTerms:${collection}:${entryId}:${taxonomyName ?? \"*\"}:${locale ?? \"*\"}`,\n\t\t\t\tload: async () => {\n\t\t\t\t\tconst db = await getDb();\n\n\t\t\t\t\tlet query = db\n\t\t\t\t\t\t.selectFrom(\"content_taxonomies\")\n\t\t\t\t\t\t.innerJoin(\n\t\t\t\t\t\t\t\"taxonomies\",\n\t\t\t\t\t\t\t\"taxonomies.translation_group\",\n\t\t\t\t\t\t\t\"content_taxonomies.taxonomy_id\",\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.selectAll(\"taxonomies\")\n\t\t\t\t\t\t.where(\"content_taxonomies.collection\", \"=\", collection)\n\t\t\t\t\t\t.where(\"content_taxonomies.entry_id\", \"=\", entryId);\n\n\t\t\t\t\tif (taxonomyName) query = query.where(\"taxonomies.name\", \"=\", taxonomyName);\n\t\t\t\t\tif (locale !== undefined) query = query.where(\"taxonomies.locale\", \"=\", locale);\n\n\t\t\t\t\tconst rows = await query.execute();\n\t\t\t\t\treturn rows.map<TaxonomyTerm>((row) => ({\n\t\t\t\t\t\tid: row.id,\n\t\t\t\t\t\tname: row.name,\n\t\t\t\t\t\tslug: row.slug,\n\t\t\t\t\t\tlabel: row.label,\n\t\t\t\t\t\tparentId: row.parent_id ?? undefined,\n\t\t\t\t\t\tchildren: [],\n\t\t\t\t\t\tlocale: row.locale,\n\t\t\t\t\t\ttranslationGroup: row.translation_group,\n\t\t\t\t\t}));\n\t\t\t\t},\n\t\t\t}),\n\t);\n}\n\n/**\n * Terms for multiple entries of one taxonomy, single query.\n */\nexport async function getTermsForEntries(\n\tcollection: string,\n\tentryIds: string[],\n\ttaxonomyName: string,\n\toptions: TaxonomyQueryOptions = {},\n): Promise<Map<string, TaxonomyTerm[]>> {\n\tconst uniqueIds = [...new Set(entryIds)];\n\tif (uniqueIds.length === 0) return new Map();\n\tconst locale = resolveLocale(options.locale);\n\tconst localeKey = locale ?? \"*\";\n\n\t// The query result is a Map, which JSON can't represent — cache it as an\n\t// array of [entryId, terms] pairs and rebuild the Map on read.\n\tconst load = async (): Promise<Array<[string, TaxonomyTerm[]]>> => {\n\t\tconst result = new Map<string, TaxonomyTerm[]>();\n\t\tfor (const id of uniqueIds) result.set(id, []);\n\n\t\t// Entry-term hydration (getAllTermsForEntries -> primeEntryTermsCache)\n\t\t// seeds the per-entry cache under the same key getEntryTerms uses:\n\t\t// `terms:${collection}:${entryId}:${taxonomyName}:${localeKey}`, storing a\n\t\t// TaxonomyTerm[] (including `[]` for entries with no terms). Satisfy those\n\t\t// from cache and run the batched query only for the ids that missed.\n\t\tconst missedIds: string[] = [];\n\t\ttype CacheRead = { id: string; terms: TaxonomyTerm[] } | { id: string; miss: true };\n\t\tconst cacheReads: Array<Promise<CacheRead>> = [];\n\t\tfor (const id of uniqueIds) {\n\t\t\tconst cached = peekRequestCache<TaxonomyTerm[]>(\n\t\t\t\t`terms:${collection}:${id}:${taxonomyName}:${localeKey}`,\n\t\t\t);\n\t\t\tif (cached) {\n\t\t\t\t// A peeked promise can reject (e.g. a sibling getEntryTerms hit a\n\t\t\t\t// missing table). Treat a rejection as a cache miss so the batched\n\t\t\t\t// query path -- and its isMissingTableError guard below -- still runs,\n\t\t\t\t// rather than propagating an uncaught error.\n\t\t\t\tcacheReads.push(\n\t\t\t\t\tcached.then(\n\t\t\t\t\t\t(terms): CacheRead => ({ id, terms }),\n\t\t\t\t\t\t(): CacheRead => ({ id, miss: true }),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tmissedIds.push(id);\n\t\t\t}\n\t\t}\n\t\tfor (const read of await Promise.all(cacheReads)) {\n\t\t\tif (\"miss\" in read) {\n\t\t\t\tmissedIds.push(read.id);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t// Return a private copy. The cached array and its term objects are shared\n\t\t\t// with getEntryTerms/getAllTermsForEntries (primeEntryTermsCache stores\n\t\t\t// the same references), so a caller that mutates the result -- sorting in\n\t\t\t// place, pushing into `children` -- must not poison the cache. The\n\t\t\t// pre-cache implementation always returned freshly built arrays.\n\t\t\tresult.set(\n\t\t\t\tread.id,\n\t\t\t\tread.terms.map((t) => ({ ...t, children: [...t.children] })),\n\t\t\t);\n\t\t}\n\n\t\tif (missedIds.length === 0) return [...result.entries()];\n\n\t\tconst db = await getDb();\n\t\tfor (const chunk of chunks(missedIds, SQL_BATCH_SIZE)) {\n\t\t\tlet rows;\n\t\t\ttry {\n\t\t\t\tlet query = db\n\t\t\t\t\t.selectFrom(\"content_taxonomies\")\n\t\t\t\t\t.innerJoin(\"taxonomies\", \"taxonomies.translation_group\", \"content_taxonomies.taxonomy_id\")\n\t\t\t\t\t.select([\n\t\t\t\t\t\t\"content_taxonomies.entry_id\",\n\t\t\t\t\t\t\"taxonomies.id\",\n\t\t\t\t\t\t\"taxonomies.name\",\n\t\t\t\t\t\t\"taxonomies.slug\",\n\t\t\t\t\t\t\"taxonomies.label\",\n\t\t\t\t\t\t\"taxonomies.parent_id\",\n\t\t\t\t\t\t\"taxonomies.locale\",\n\t\t\t\t\t\t\"taxonomies.translation_group\",\n\t\t\t\t\t])\n\t\t\t\t\t.where(\"content_taxonomies.collection\", \"=\", collection)\n\t\t\t\t\t.where(\"content_taxonomies.entry_id\", \"in\", chunk)\n\t\t\t\t\t.where(\"taxonomies.name\", \"=\", taxonomyName)\n\t\t\t\t\t// Match the order getAllTermsForEntries (the cache primer) uses, so\n\t\t\t\t\t// cache-hit and DB-miss entries in one result are ordered consistently.\n\t\t\t\t\t.orderBy(\"taxonomies.label\", \"asc\");\n\t\t\t\tif (locale !== undefined) query = query.where(\"taxonomies.locale\", \"=\", locale);\n\t\t\t\trows = await query.execute();\n\t\t\t} catch (error) {\n\t\t\t\tif (isMissingTableError(error)) return [...result.entries()];\n\t\t\t\tthrow error;\n\t\t\t}\n\n\t\t\tfor (const row of rows) {\n\t\t\t\tconst term: TaxonomyTerm = {\n\t\t\t\t\tid: row.id,\n\t\t\t\t\tname: row.name,\n\t\t\t\t\tslug: row.slug,\n\t\t\t\t\tlabel: row.label,\n\t\t\t\t\tparentId: row.parent_id ?? undefined,\n\t\t\t\t\tchildren: [],\n\t\t\t\t\tlocale: row.locale,\n\t\t\t\t\ttranslationGroup: row.translation_group,\n\t\t\t\t};\n\t\t\t\tconst terms = result.get(row.entry_id);\n\t\t\t\tif (terms) terms.push(term);\n\t\t\t}\n\t\t}\n\n\t\treturn [...result.entries()];\n\t};\n\n\t// Key on the sorted unique ids. Bound the key length: very large batches\n\t// (rare; they come from collection hydration, already served by the content\n\t// cache) bypass the object cache rather than blow past KV's key limit.\n\tconst idKey = uniqueIds.toSorted().join(\",\");\n\tconst pairs =\n\t\tidKey.length <= 256\n\t\t\t? await cachedQuery({\n\t\t\t\t\tnamespace: [contentNamespace(collection), CacheNamespace.TAXONOMIES],\n\t\t\t\t\tkey: `termsForEntries:${collection}:${taxonomyName}:${locale ?? \"*\"}:${idKey}`,\n\t\t\t\t\tload,\n\t\t\t\t})\n\t\t\t: await load();\n\n\treturn new Map(pairs);\n}\n\n/**\n * Batch-fetch terms for multiple entries across ALL taxonomies in one query.\n * Primes the request-cache for subsequent per-entry calls to `getEntryTerms`.\n */\nexport async function getAllTermsForEntries(\n\tcollection: string,\n\tentryIds: string[],\n\toptions: TaxonomyQueryOptions = {},\n): Promise<Map<string, Record<string, TaxonomyTerm[]>>> {\n\tconst result = new Map<string, Record<string, TaxonomyTerm[]>>();\n\tconst uniqueIds = [...new Set(entryIds)];\n\tfor (const id of uniqueIds) result.set(id, {});\n\tif (uniqueIds.length === 0) return result;\n\n\tconst db = await getDb();\n\tconst locale = resolveLocale(options.locale);\n\tconst applicableTaxonomyNames = await getCollectionTaxonomyNames(collection, { locale });\n\n\tfor (const chunk of chunks(uniqueIds, SQL_BATCH_SIZE)) {\n\t\tlet rows;\n\t\ttry {\n\t\t\tlet query = db\n\t\t\t\t.selectFrom(\"content_taxonomies\")\n\t\t\t\t.innerJoin(\"taxonomies\", \"taxonomies.translation_group\", \"content_taxonomies.taxonomy_id\")\n\t\t\t\t.select([\n\t\t\t\t\t\"content_taxonomies.entry_id\",\n\t\t\t\t\t\"taxonomies.id\",\n\t\t\t\t\t\"taxonomies.name\",\n\t\t\t\t\t\"taxonomies.slug\",\n\t\t\t\t\t\"taxonomies.label\",\n\t\t\t\t\t\"taxonomies.parent_id\",\n\t\t\t\t\t\"taxonomies.locale\",\n\t\t\t\t\t\"taxonomies.translation_group\",\n\t\t\t\t])\n\t\t\t\t.where(\"content_taxonomies.collection\", \"=\", collection)\n\t\t\t\t.where(\"content_taxonomies.entry_id\", \"in\", chunk)\n\t\t\t\t.orderBy(\"taxonomies.label\", \"asc\");\n\t\t\tif (locale !== undefined) query = query.where(\"taxonomies.locale\", \"=\", locale);\n\t\t\trows = await query.execute();\n\t\t} catch (error) {\n\t\t\tif (isMissingTableError(error)) {\n\t\t\t\tfor (const id of uniqueIds) {\n\t\t\t\t\tprimeEntryTermsCache(collection, id, {}, applicableTaxonomyNames, locale);\n\t\t\t\t}\n\t\t\t\treturn result;\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\n\t\tfor (const row of rows) {\n\t\t\tconst term: TaxonomyTerm = {\n\t\t\t\tid: row.id,\n\t\t\t\tname: row.name,\n\t\t\t\tslug: row.slug,\n\t\t\t\tlabel: row.label,\n\t\t\t\tparentId: row.parent_id ?? undefined,\n\t\t\t\tchildren: [],\n\t\t\t\tlocale: row.locale,\n\t\t\t\ttranslationGroup: row.translation_group,\n\t\t\t};\n\t\t\tconst byTaxonomy = result.get(row.entry_id);\n\t\t\tif (!byTaxonomy) continue;\n\t\t\tconst existing = byTaxonomy[row.name];\n\t\t\tif (existing) existing.push(term);\n\t\t\telse byTaxonomy[row.name] = [term];\n\t\t}\n\t}\n\n\tfor (const [entryId, byTaxonomy] of result) {\n\t\tprimeEntryTermsCache(collection, entryId, byTaxonomy, applicableTaxonomyNames, locale);\n\t}\n\n\treturn result;\n}\n\n/**\n * Return the list of taxonomy names applicable to a collection, request-\n * cached so a page render only pays for it once.\n *\n * Returns an empty list when taxonomies haven't been defined yet.\n */\nasync function getCollectionTaxonomyNames(\n\tcollection: string,\n\toptions: TaxonomyQueryOptions,\n): Promise<string[]> {\n\ttry {\n\t\tconst defs = await getTaxonomyDefs(options);\n\t\treturn defs.filter((d) => d.collections.includes(collection)).map((d) => d.name);\n\t} catch (error) {\n\t\tif (isMissingTableError(error)) return [];\n\t\tthrow error;\n\t}\n}\n\n/**\n * Pre-populate the request-cache for every getEntryTerms call-shape that\n * could hit this entry:\n *\n * getEntryTerms(collection, entryId) -> key `terms:C:E:*`\n * getEntryTerms(collection, entryId, \"tag\") -> key `terms:C:E:tag`\n * getEntryTerms(collection, entryId, \"category\") -> key `terms:C:E:category`\n * ...one per taxonomy that applies to this collection\n *\n * Taxonomies with no rows on this entry are seeded with `[]` so legacy\n * callers short-circuit to the cached empty array instead of re-querying.\n */\nfunction primeEntryTermsCache(\n\tcollection: string,\n\tentryId: string,\n\tbyTaxonomy: Record<string, TaxonomyTerm[]>,\n\tapplicableTaxonomyNames: string[],\n\tlocale: string | undefined,\n): void {\n\tconst localeKey = locale ?? \"*\";\n\tfor (const name of applicableTaxonomyNames) {\n\t\tsetRequestCacheEntry(\n\t\t\t`terms:${collection}:${entryId}:${name}:${localeKey}`,\n\t\t\tbyTaxonomy[name] ?? [],\n\t\t);\n\t}\n\tfor (const [name, terms] of Object.entries(byTaxonomy)) {\n\t\tsetRequestCacheEntry(`terms:${collection}:${entryId}:${name}:${localeKey}`, terms);\n\t}\n\tconst allTerms = Object.values(byTaxonomy).flat();\n\tsetRequestCacheEntry(`terms:${collection}:${entryId}:*:${localeKey}`, allTerms);\n}\n\n/**\n * Prime the per-entry request cache from terms that were folded into the\n * content query (query.ts `hydrateEntryTerms` fast path), so subsequent\n * `getEntryTerms` calls in the same render hit the cache instead of issuing an\n * N+1 query. Seeds the wildcard key and one key per taxonomy present on the\n * entry — purely from the folded data, with no DB lookup.\n *\n * Unlike `getAllTermsForEntries`, this deliberately does NOT seed `[]` for\n * taxonomies that apply to the collection but have no rows on the entry: doing\n * so would require a `getTaxonomyDefs` query, adding a round trip to every fold\n * render to serve the rarer `getEntryTerms(id, absentTaxonomy)` case from cache.\n * That call simply falls through to its own cached query. Keeping the key shape\n * here (rather than in query.ts) prevents the two from drifting.\n */\nexport function primeFoldedEntryTerms(\n\tcollection: string,\n\tperEntry: Array<{ entryId: string; byTaxonomy: Record<string, TaxonomyTerm[]> }>,\n\toptions: TaxonomyQueryOptions = {},\n): void {\n\tif (perEntry.length === 0) return;\n\tconst locale = resolveLocale(options.locale);\n\tfor (const { entryId, byTaxonomy } of perEntry) {\n\t\tprimeEntryTermsCache(collection, entryId, byTaxonomy, [], locale);\n\t}\n}\n\n/**\n * Get entries by term. Both the lookup (term slug in the active locale) and\n * the content query respect the active locale.\n */\nexport async function getEntriesByTerm(\n\tcollection: string,\n\ttaxonomyName: string,\n\ttermSlug: string,\n\toptions: TaxonomyQueryOptions = {},\n): Promise<Array<{ id: string; data: Record<string, unknown> }>> {\n\tconst { getEmDashCollection } = await import(\"../query.js\");\n\n\tconst queryOptions: Record<string, unknown> = {\n\t\twhere: { [taxonomyName]: termSlug },\n\t};\n\tif (options.locale !== undefined) queryOptions.locale = options.locale;\n\tconst { entries } = await getEmDashCollection(collection, queryOptions);\n\treturn entries;\n}\n\nfunction rowToTaxonomyDef(row: {\n\tid: string;\n\tname: string;\n\tlabel: string;\n\tlabel_singular: string | null;\n\thierarchical: number;\n\tcollections: string | null;\n\tlocale: string;\n\ttranslation_group: string | null;\n}): TaxonomyDef {\n\treturn {\n\t\tid: row.id,\n\t\tname: row.name,\n\t\tlabel: row.label,\n\t\tlabelSingular: row.label_singular ?? undefined,\n\t\thierarchical: row.hierarchical === 1,\n\t\tcollections: row.collections ? JSON.parse(row.collections) : [],\n\t\tlocale: row.locale,\n\t\ttranslationGroup: row.translation_group,\n\t};\n}\n\n/**\n * Build tree structure from flat terms\n */\nfunction buildTree(flatTerms: TaxonomyTermRow[], counts: Map<string, number>): TaxonomyTerm[] {\n\t// parent_id holds the parent's translation_group, so link children by it.\n\t// Key by (locale, group): a child's parent lives in the same locale, and an\n\t// unfiltered set mixes locales whose translated siblings share a group —\n\t// keying by group alone would collide and misattach children across locales.\n\tconst byLocaleGroup = new Map<string, TaxonomyTerm>();\n\tconst nodes: TaxonomyTerm[] = [];\n\tconst roots: TaxonomyTerm[] = [];\n\n\tfor (const term of flatTerms) {\n\t\tconst node: TaxonomyTerm = {\n\t\t\tid: term.id,\n\t\t\tname: term.name,\n\t\t\tslug: term.slug,\n\t\t\tlabel: term.label,\n\t\t\tparentId: term.parent_id ?? undefined,\n\t\t\tdescription: term.data ? JSON.parse(term.data).description : undefined,\n\t\t\tchildren: [],\n\t\t\tcount: counts.get(term.translation_group ?? term.id) ?? 0,\n\t\t\tlocale: term.locale,\n\t\t\ttranslationGroup: term.translation_group,\n\t\t};\n\t\tbyLocaleGroup.set(`${term.locale}::${term.translation_group ?? term.id}`, node);\n\t\tnodes.push(node);\n\t}\n\n\tfor (const node of nodes) {\n\t\tconst parent = node.parentId\n\t\t\t? byLocaleGroup.get(`${node.locale}::${node.parentId}`)\n\t\t\t: undefined;\n\t\tif (parent) {\n\t\t\tparent.children.push(node);\n\t\t} else {\n\t\t\troots.push(node);\n\t\t}\n\t}\n\n\treturn roots;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCA,SAAgB,sBAA4B;AAC3C,gCAA+B;;AAiChC,MAAM,0BAA0B,OAAO,IAAI,uBAAuB;AAClE,MAAM,oBAAoB;AAC1B,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;CACrD,MAAM,QAAwB,EAAE;CAChC,MAAM,QAAwB,EAAE;AAEhC,MAAK,MAAM,QAAQ,WAAW;EAC7B,MAAM,OAAqB;GAC1B,IAAI,KAAK;GACT,MAAM,KAAK;GACX,MAAM,KAAK;GACX,OAAO,KAAK;GACZ,UAAU,KAAK,aAAa;GAC5B,aAAa,KAAK,OAAO,KAAK,MAAM,KAAK,KAAK,CAAC,cAAc;GAC7D,UAAU,EAAE;GACZ,OAAO,OAAO,IAAI,KAAK,qBAAqB,KAAK,GAAG,IAAI;GACxD,QAAQ,KAAK;GACb,kBAAkB,KAAK;GACvB;AACD,gBAAc,IAAI,GAAG,KAAK,OAAO,IAAI,KAAK,qBAAqB,KAAK,MAAM,KAAK;AAC/E,QAAM,KAAK,KAAK;;AAGjB,MAAK,MAAM,QAAQ,OAAO;EACzB,MAAM,SAAS,KAAK,WACjB,cAAc,IAAI,GAAG,KAAK,OAAO,IAAI,KAAK,WAAW,GACrD;AACH,MAAI,OACH,QAAO,SAAS,KAAK,KAAK;MAE1B,OAAM,KAAK,KAAK;;AAIlB,QAAO"}
|
|
1
|
+
{"version":3,"file":"taxonomies-kH9ABDUF.mjs","names":[],"sources":["../src/taxonomies/index.ts"],"sourcesContent":["/**\n * Runtime API for taxonomies.\n *\n * All helpers are locale-aware. When a locale is not passed explicitly we fall\n * back to the request context or the configured `defaultLocale` (see\n * `i18n/resolve.ts`).\n *\n * Because `content_taxonomies.taxonomy_id` stores the translation_group (not a\n * specific term id), the joins here are `taxonomies.translation_group =\n * content_taxonomies.taxonomy_id` + filter by `taxonomies.locale`, which picks\n * the right per-locale term.\n */\n\nimport { resolveLocale, resolveLocaleChain } from \"../i18n/resolve.js\";\nimport { getDb, resetTaxonomyNamesCache } from \"../loader.js\";\nimport {\n\tcachedQuery,\n\tCacheNamespace,\n\tcontentNamespace,\n\tinvalidateTaxonomyObjectCache,\n\tisObjectCacheActive,\n} from \"../object-cache/index.js\";\nimport { peekRequestCache, requestCached, setRequestCacheEntry } from \"../request-cache.js\";\nimport { getRequestContext } from \"../request-context.js\";\nimport { chunks, SQL_BATCH_SIZE } from \"../utils/chunks.js\";\nimport { isMissingTableError } from \"../utils/db-errors.js\";\nimport type { TaxonomyDef, TaxonomyTerm, TaxonomyTermRow } from \"./types.js\";\n\nexport interface TaxonomyQueryOptions {\n\tlocale?: string;\n}\n\n/** Invalidate cached taxonomy term data and any content that hydrates terms. */\nexport function invalidateTermCache(): void {\n\tinvalidateTaxonomyObjectCache();\n}\n\n/**\n * Worker-isolate cache for taxonomy definitions, keyed by resolved locale.\n *\n * Taxonomy *definitions* (the \"category\"/\"tag\" taxonomies themselves, not\n * their terms) are read on every public render that hydrates entry terms —\n * `getAllTermsForEntries` → `getCollectionTaxonomyNames` → `getTaxonomyDefs` —\n * but change extremely rarely: they're created via the admin API or applied\n * from a seed, and there is no edit/delete-def path. Caching them across the\n * isolate lifetime drops the per-render `SELECT * FROM _emdash_taxonomy_defs`\n * to once-per-isolate.\n *\n * Stored on globalThis behind a Symbol key (same pattern as\n * `settings/index.ts`) so the bundler duplicating this module across SSR\n * chunks can't produce two independent caches.\n *\n * When the distributed object cache is configured, it is authoritative and this\n * fallback is bypassed so cross-isolate epoch invalidation cannot be undercut\n * by stale per-isolate data on an object-cache miss.\n *\n * **Isolated databases bypass the cache.** Playground / DO preview requests\n * set `requestContext.dbIsIsolated`; they point at a divergent schema, so we\n * skip both reading and writing the global holder and fall back to the\n * per-request cache (same precedent as `getTaxonomyNames` / byline field defs).\n */\ninterface TaxonomyDefsHolder {\n\tversion: number;\n\t/** locale key (\"*\" for \"all locales\") → { version it was fetched at, promise }. */\n\tcache: Map<string, { version: number; promise: Promise<TaxonomyDef[]> }>;\n}\n\nconst TAXONOMY_DEFS_CACHE_KEY = Symbol.for(\"emdash:taxonomy-defs\");\nconst taxonomyDefsStore = globalThis as Record<symbol, unknown>;\nconst defsHolder: TaxonomyDefsHolder =\n\t// eslint-disable-next-line typescript/no-unsafe-type-assertion -- globalThis singleton pattern (see settings/index.ts)\n\t(taxonomyDefsStore[TAXONOMY_DEFS_CACHE_KEY] as TaxonomyDefsHolder | undefined) ??\n\t(() => {\n\t\tconst h: TaxonomyDefsHolder = { version: 0, cache: new Map() };\n\t\ttaxonomyDefsStore[TAXONOMY_DEFS_CACHE_KEY] = h;\n\t\treturn h;\n\t})();\n\n/**\n * Invalidate the isolate-wide taxonomy-definitions cache (and the related\n * loader taxonomy-names cache). Called from every taxonomy-def write path\n * (`handleTaxonomyCreate`, seed application). Other isolates refresh on their\n * next recycle — staleness bounded by isolate lifetime.\n */\nexport function invalidateTaxonomyDefsCache(): void {\n\tdefsHolder.version++;\n\tdefsHolder.cache.clear();\n\tresetTaxonomyNamesCache();\n\tinvalidateTaxonomyObjectCache();\n}\n\n/**\n * Test/internal helper: clear the per-isolate taxonomy-defs cache. Useful for\n * unit tests that insert defs directly and need to force a refetch without\n * going through a write path. Production code should rely on\n * `invalidateTaxonomyDefsCache()`.\n */\nexport function resetTaxonomyDefsCacheForTests(): void {\n\tdefsHolder.version++;\n\tdefsHolder.cache.clear();\n}\n\n/**\n * Fetch taxonomy definitions straight from the database (no caching).\n */\nasync function fetchTaxonomyDefs(locale: string | undefined): Promise<TaxonomyDef[]> {\n\tconst db = await getDb();\n\tlet query = db.selectFrom(\"_emdash_taxonomy_defs\").selectAll();\n\tif (locale !== undefined) query = query.where(\"locale\", \"=\", locale);\n\tconst rows = await query.execute();\n\treturn rows.map(rowToTaxonomyDef);\n}\n\n/**\n * Resolve taxonomy defs through the isolate fallback cache, bypassing it for\n * isolated databases. The returned promise is cached (not the resolved value)\n * so concurrent cold-isolate readers share one in-flight query; a rejection\n * evicts the entry so the next caller retries.\n */\nfunction loadTaxonomyDefs(localeKey: string, locale: string | undefined): Promise<TaxonomyDef[]> {\n\tif (getRequestContext()?.dbIsIsolated === true) {\n\t\treturn fetchTaxonomyDefs(locale);\n\t}\n\tconst existing = defsHolder.cache.get(localeKey);\n\tif (existing && existing.version === defsHolder.version) {\n\t\treturn existing.promise;\n\t}\n\tconst version = defsHolder.version;\n\tconst promise = fetchTaxonomyDefs(locale).catch((error: unknown) => {\n\t\tconst current = defsHolder.cache.get(localeKey);\n\t\tif (current && current.promise === promise) {\n\t\t\tdefsHolder.cache.delete(localeKey);\n\t\t}\n\t\tthrow error;\n\t});\n\tdefsHolder.cache.set(localeKey, { version, promise });\n\treturn promise;\n}\n\n/**\n * Get every taxonomy definition. Definitions are per-locale (one row per\n * locale inside the same translation_group) — by default we resolve to the\n * active locale.\n *\n * Two-tier cache: per-request via `requestCached` (so a single render that\n * hydrates terms for several collections pays at most one call), then\n * per-isolate via the global holder (so warm renders issue zero queries).\n * The `requestCached` key is unchanged so `getTaxonomyDef`'s peek still hits.\n */\nexport async function getTaxonomyDefs(options: TaxonomyQueryOptions = {}): Promise<TaxonomyDef[]> {\n\tconst locale = resolveLocale(options.locale);\n\tconst localeKey = locale ?? \"*\";\n\treturn requestCached(`taxonomy-defs:${localeKey}`, async () => {\n\t\tif (await isObjectCacheActive()) {\n\t\t\treturn cachedQuery({\n\t\t\t\tnamespace: CacheNamespace.TAXONOMIES,\n\t\t\t\tkey: `defs:${localeKey}`,\n\t\t\t\tload: () => fetchTaxonomyDefs(locale),\n\t\t\t});\n\t\t}\n\t\treturn loadTaxonomyDefs(localeKey, locale);\n\t});\n}\n\n/**\n * Get a single taxonomy definition by name. Uses the fallback chain so even\n * if there is no translation for the active locale we still return something.\n *\n * If `getTaxonomyDefs()` has already loaded the full list in this request\n * (which happens during entry-term hydration on every page that renders a\n * collection), search the matching def in memory rather than running a\n * second query against `_emdash_taxonomy_defs`.\n */\nexport async function getTaxonomyDef(\n\tname: string,\n\toptions: TaxonomyQueryOptions = {},\n): Promise<TaxonomyDef | null> {\n\tconst chain = resolveLocaleChain(options.locale);\n\tconst peekKey = `taxonomy-defs:${resolveLocale(options.locale) ?? \"*\"}`;\n\tconst allDefs = peekRequestCache<TaxonomyDef[]>(peekKey);\n\tif (allDefs) {\n\t\tconst defs = await allDefs;\n\t\tif (chain.length === 0) return defs.find((d) => d.name === name) ?? null;\n\t\tfor (const locale of chain) {\n\t\t\tconst found = defs.find((d) => d.name === name && d.locale === locale);\n\t\t\tif (found) return found;\n\t\t}\n\t\treturn null;\n\t}\n\n\treturn requestCached(`taxonomy-def:${name}:${chain.join(\",\")}`, async () => {\n\t\tconst db = await getDb();\n\n\t\tif (chain.length === 0) {\n\t\t\tconst row = await db\n\t\t\t\t.selectFrom(\"_emdash_taxonomy_defs\")\n\t\t\t\t.selectAll()\n\t\t\t\t.where(\"name\", \"=\", name)\n\t\t\t\t.orderBy(\"locale\", \"asc\")\n\t\t\t\t.executeTakeFirst();\n\t\t\treturn row ? rowToTaxonomyDef(row) : null;\n\t\t}\n\n\t\tfor (const locale of chain) {\n\t\t\tconst row = await db\n\t\t\t\t.selectFrom(\"_emdash_taxonomy_defs\")\n\t\t\t\t.selectAll()\n\t\t\t\t.where(\"name\", \"=\", name)\n\t\t\t\t.where(\"locale\", \"=\", locale)\n\t\t\t\t.executeTakeFirst();\n\t\t\tif (row) return rowToTaxonomyDef(row);\n\t\t}\n\t\treturn null;\n\t});\n}\n\n/**\n * All terms of a taxonomy in a specific locale (flat for non-hierarchical,\n * tree for hierarchical).\n */\nexport async function getTaxonomyTerms(\n\ttaxonomyName: string,\n\toptions: TaxonomyQueryOptions = {},\n): Promise<TaxonomyTerm[]> {\n\tconst locale = resolveLocale(options.locale);\n\treturn requestCached(`taxonomy-terms:${taxonomyName}:${locale ?? \"*\"}`, () =>\n\t\tcachedQuery({\n\t\t\tnamespace: CacheNamespace.TAXONOMIES,\n\t\t\tkey: `terms:${taxonomyName}:${locale ?? \"*\"}`,\n\t\t\tload: () => loadTaxonomyTerms(taxonomyName, locale, options),\n\t\t}),\n\t);\n}\n\nasync function loadTaxonomyTerms(\n\ttaxonomyName: string,\n\tlocale: string | undefined,\n\toptions: TaxonomyQueryOptions,\n): Promise<TaxonomyTerm[]> {\n\tconst db = await getDb();\n\n\tconst def = await getTaxonomyDef(taxonomyName, options);\n\tif (!def) return [];\n\n\tlet termsQuery = db\n\t\t.selectFrom(\"taxonomies\")\n\t\t.selectAll()\n\t\t.where(\"name\", \"=\", taxonomyName)\n\t\t.orderBy(\"label\", \"asc\");\n\tif (locale !== undefined) termsQuery = termsQuery.where(\"locale\", \"=\", locale);\n\tconst rows = await termsQuery.execute();\n\n\t// Counts are keyed by translation_group (what the pivot stores) and are\n\t// locale-independent, so the aggregate is shared across every taxonomy\n\t// rendered in this request (Categories + Tags widgets, etc.).\n\tconst counts = await getTaxonomyTermCounts();\n\n\tconst flatTerms: TaxonomyTermRow[] = rows.map((row) => ({\n\t\tid: row.id,\n\t\tname: row.name,\n\t\tslug: row.slug,\n\t\tlabel: row.label,\n\t\tparent_id: row.parent_id,\n\t\tdata: row.data,\n\t\tlocale: row.locale,\n\t\ttranslation_group: row.translation_group,\n\t}));\n\n\tif (def.hierarchical) return buildTree(flatTerms, counts);\n\n\treturn flatTerms.map((term) => ({\n\t\tid: term.id,\n\t\tname: term.name,\n\t\tslug: term.slug,\n\t\tlabel: term.label,\n\t\tdescription: term.data ? JSON.parse(term.data).description : undefined,\n\t\tchildren: [],\n\t\tcount: counts.get(term.translation_group ?? term.id) ?? 0,\n\t\tlocale: term.locale,\n\t\ttranslationGroup: term.translation_group,\n\t}));\n}\n\n/**\n * Per-translation-group usage counts across all taxonomies, in one aggregate\n * scan of `content_taxonomies`. Counts are locale-independent (the pivot stores\n * translation_group), so a single request-cached entry serves every taxonomy\n * that renders during the request.\n */\nfunction getTaxonomyTermCounts(): Promise<Map<string, number>> {\n\treturn requestCached(\"taxonomy-term-counts\", async () => {\n\t\tconst db = await getDb();\n\t\tconst countsResult = await db\n\t\t\t.selectFrom(\"content_taxonomies\")\n\t\t\t.select([\"taxonomy_id\"])\n\t\t\t.select((eb) => eb.fn.count<number>(\"entry_id\").as(\"count\"))\n\t\t\t.groupBy(\"taxonomy_id\")\n\t\t\t.execute();\n\t\tconst counts = new Map<string, number>();\n\t\tfor (const row of countsResult) counts.set(row.taxonomy_id, row.count);\n\t\treturn counts;\n\t});\n}\n\n/**\n * Get a single term by (taxonomy, slug). Honours the fallback chain — if the\n * slug exists in a fallback locale, we return that row (useful for deep-linking\n * to a term page when the translation is missing).\n */\nexport async function getTerm(\n\ttaxonomyName: string,\n\tslug: string,\n\toptions: TaxonomyQueryOptions = {},\n): Promise<TaxonomyTerm | null> {\n\tconst chain = resolveLocaleChain(options.locale);\n\t// Cached under the shared taxonomies epoch (bumped on any taxonomy / term\n\t// assignment write). The `count` reflects content_taxonomies rows; a stale\n\t// count after a bare content delete is bounded by the entry's TTL.\n\treturn cachedQuery({\n\t\tnamespace: CacheNamespace.TAXONOMIES,\n\t\tkey: `term:${taxonomyName}:${slug}:${chain.join(\",\")}`,\n\t\tload: () => loadTerm(taxonomyName, slug, chain),\n\t});\n}\n\nasync function loadTerm(\n\ttaxonomyName: string,\n\tslug: string,\n\tchain: string[],\n): Promise<TaxonomyTerm | null> {\n\tconst db = await getDb();\n\n\tlet row: Awaited<ReturnType<ReturnType<typeof selectTerm>[\"executeTakeFirst\"]>>;\n\tconst selectTerm = () =>\n\t\tdb\n\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t.selectAll()\n\t\t\t.where(\"name\", \"=\", taxonomyName)\n\t\t\t.where(\"slug\", \"=\", slug);\n\n\tif (chain.length === 0) {\n\t\trow = await selectTerm().orderBy(\"locale\", \"asc\").executeTakeFirst();\n\t} else {\n\t\trow = undefined;\n\t\tfor (const locale of chain) {\n\t\t\trow = await selectTerm().where(\"locale\", \"=\", locale).executeTakeFirst();\n\t\t\tif (row) break;\n\t\t}\n\t}\n\n\tif (!row) return null;\n\n\tlet childrenQuery = db\n\t\t.selectFrom(\"taxonomies\")\n\t\t.selectAll()\n\t\t// Children store the parent's translation_group in parent_id (not a row\n\t\t// id), so a translated parent still owns its children in its own locale.\n\t\t.where(\"parent_id\", \"=\", row.translation_group ?? row.id)\n\t\t.orderBy(\"label\", \"asc\");\n\tconst termLocale = row.locale;\n\tif (termLocale) childrenQuery = childrenQuery.where(\"locale\", \"=\", termLocale);\n\n\t// The usage-count and children queries both depend only on the term row,\n\t// so run them concurrently to save a round trip on remote databases.\n\tconst [countResult, childRows] = await Promise.all([\n\t\tdb\n\t\t\t.selectFrom(\"content_taxonomies\")\n\t\t\t.select((eb) => eb.fn.count<number>(\"entry_id\").as(\"count\"))\n\t\t\t.where(\"taxonomy_id\", \"=\", row.translation_group ?? row.id)\n\t\t\t.executeTakeFirst(),\n\t\tchildrenQuery.execute(),\n\t]);\n\tconst count = countResult?.count ?? 0;\n\n\tconst children = childRows.map<TaxonomyTerm>((child) => ({\n\t\tid: child.id,\n\t\tname: child.name,\n\t\tslug: child.slug,\n\t\tlabel: child.label,\n\t\tparentId: child.parent_id ?? undefined,\n\t\tchildren: [],\n\t\tlocale: child.locale,\n\t\ttranslationGroup: child.translation_group,\n\t}));\n\n\treturn {\n\t\tid: row.id,\n\t\tname: row.name,\n\t\tslug: row.slug,\n\t\tlabel: row.label,\n\t\tparentId: row.parent_id ?? undefined,\n\t\tdescription: row.data ? JSON.parse(row.data).description : undefined,\n\t\tchildren,\n\t\tcount,\n\t\tlocale: row.locale,\n\t\ttranslationGroup: row.translation_group,\n\t};\n}\n\n/**\n * Terms assigned to a content entry, resolved into the active locale. Terms\n * whose translation_group lacks a row in the requested locale are omitted.\n */\nexport function getEntryTerms(\n\tcollection: string,\n\tentryId: string,\n\ttaxonomyName?: string,\n\toptions: TaxonomyQueryOptions = {},\n): Promise<TaxonomyTerm[]> {\n\tconst locale = resolveLocale(options.locale);\n\t// requestCached short-circuits to values primed by getAllTermsForEntries\n\t// during entry hydration (same key shape). On a warm content-cache hit\n\t// hydration doesn't run, so the inner cachedQuery serves this from KV\n\t// instead of falling through to D1 on every request.\n\treturn requestCached(\n\t\t`terms:${collection}:${entryId}:${taxonomyName ?? \"*\"}:${locale ?? \"*\"}`,\n\t\t() =>\n\t\t\tcachedQuery({\n\t\t\t\tnamespace: [contentNamespace(collection), CacheNamespace.TAXONOMIES],\n\t\t\t\tkey: `entryTerms:${collection}:${entryId}:${taxonomyName ?? \"*\"}:${locale ?? \"*\"}`,\n\t\t\t\tload: async () => {\n\t\t\t\t\tconst db = await getDb();\n\n\t\t\t\t\tlet query = db\n\t\t\t\t\t\t.selectFrom(\"content_taxonomies\")\n\t\t\t\t\t\t.innerJoin(\n\t\t\t\t\t\t\t\"taxonomies\",\n\t\t\t\t\t\t\t\"taxonomies.translation_group\",\n\t\t\t\t\t\t\t\"content_taxonomies.taxonomy_id\",\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.selectAll(\"taxonomies\")\n\t\t\t\t\t\t.where(\"content_taxonomies.collection\", \"=\", collection)\n\t\t\t\t\t\t.where(\"content_taxonomies.entry_id\", \"=\", entryId);\n\n\t\t\t\t\tif (taxonomyName) query = query.where(\"taxonomies.name\", \"=\", taxonomyName);\n\t\t\t\t\tif (locale !== undefined) query = query.where(\"taxonomies.locale\", \"=\", locale);\n\n\t\t\t\t\tconst rows = await query.execute();\n\t\t\t\t\treturn rows.map<TaxonomyTerm>((row) => ({\n\t\t\t\t\t\tid: row.id,\n\t\t\t\t\t\tname: row.name,\n\t\t\t\t\t\tslug: row.slug,\n\t\t\t\t\t\tlabel: row.label,\n\t\t\t\t\t\tparentId: row.parent_id ?? undefined,\n\t\t\t\t\t\tchildren: [],\n\t\t\t\t\t\tlocale: row.locale,\n\t\t\t\t\t\ttranslationGroup: row.translation_group,\n\t\t\t\t\t}));\n\t\t\t\t},\n\t\t\t}),\n\t);\n}\n\n/**\n * Terms for multiple entries of one taxonomy, single query.\n */\nexport async function getTermsForEntries(\n\tcollection: string,\n\tentryIds: string[],\n\ttaxonomyName: string,\n\toptions: TaxonomyQueryOptions = {},\n): Promise<Map<string, TaxonomyTerm[]>> {\n\tconst uniqueIds = [...new Set(entryIds)];\n\tif (uniqueIds.length === 0) return new Map();\n\tconst locale = resolveLocale(options.locale);\n\tconst localeKey = locale ?? \"*\";\n\n\t// The query result is a Map, which JSON can't represent — cache it as an\n\t// array of [entryId, terms] pairs and rebuild the Map on read.\n\tconst load = async (): Promise<Array<[string, TaxonomyTerm[]]>> => {\n\t\tconst result = new Map<string, TaxonomyTerm[]>();\n\t\tfor (const id of uniqueIds) result.set(id, []);\n\n\t\t// Entry-term hydration (getAllTermsForEntries -> primeEntryTermsCache)\n\t\t// seeds the per-entry cache under the same key getEntryTerms uses:\n\t\t// `terms:${collection}:${entryId}:${taxonomyName}:${localeKey}`, storing a\n\t\t// TaxonomyTerm[] (including `[]` for entries with no terms). Satisfy those\n\t\t// from cache and run the batched query only for the ids that missed.\n\t\tconst missedIds: string[] = [];\n\t\ttype CacheRead = { id: string; terms: TaxonomyTerm[] } | { id: string; miss: true };\n\t\tconst cacheReads: Array<Promise<CacheRead>> = [];\n\t\tfor (const id of uniqueIds) {\n\t\t\tconst cached = peekRequestCache<TaxonomyTerm[]>(\n\t\t\t\t`terms:${collection}:${id}:${taxonomyName}:${localeKey}`,\n\t\t\t);\n\t\t\tif (cached) {\n\t\t\t\t// A peeked promise can reject (e.g. a sibling getEntryTerms hit a\n\t\t\t\t// missing table). Treat a rejection as a cache miss so the batched\n\t\t\t\t// query path -- and its isMissingTableError guard below -- still runs,\n\t\t\t\t// rather than propagating an uncaught error.\n\t\t\t\tcacheReads.push(\n\t\t\t\t\tcached.then(\n\t\t\t\t\t\t(terms): CacheRead => ({ id, terms }),\n\t\t\t\t\t\t(): CacheRead => ({ id, miss: true }),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tmissedIds.push(id);\n\t\t\t}\n\t\t}\n\t\tfor (const read of await Promise.all(cacheReads)) {\n\t\t\tif (\"miss\" in read) {\n\t\t\t\tmissedIds.push(read.id);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t// Return a private copy. The cached array and its term objects are shared\n\t\t\t// with getEntryTerms/getAllTermsForEntries (primeEntryTermsCache stores\n\t\t\t// the same references), so a caller that mutates the result -- sorting in\n\t\t\t// place, pushing into `children` -- must not poison the cache. The\n\t\t\t// pre-cache implementation always returned freshly built arrays.\n\t\t\tresult.set(\n\t\t\t\tread.id,\n\t\t\t\tread.terms.map((t) => ({ ...t, children: [...t.children] })),\n\t\t\t);\n\t\t}\n\n\t\tif (missedIds.length === 0) return [...result.entries()];\n\n\t\tconst db = await getDb();\n\t\tfor (const chunk of chunks(missedIds, SQL_BATCH_SIZE)) {\n\t\t\tlet rows;\n\t\t\ttry {\n\t\t\t\tlet query = db\n\t\t\t\t\t.selectFrom(\"content_taxonomies\")\n\t\t\t\t\t.innerJoin(\"taxonomies\", \"taxonomies.translation_group\", \"content_taxonomies.taxonomy_id\")\n\t\t\t\t\t.select([\n\t\t\t\t\t\t\"content_taxonomies.entry_id\",\n\t\t\t\t\t\t\"taxonomies.id\",\n\t\t\t\t\t\t\"taxonomies.name\",\n\t\t\t\t\t\t\"taxonomies.slug\",\n\t\t\t\t\t\t\"taxonomies.label\",\n\t\t\t\t\t\t\"taxonomies.parent_id\",\n\t\t\t\t\t\t\"taxonomies.locale\",\n\t\t\t\t\t\t\"taxonomies.translation_group\",\n\t\t\t\t\t])\n\t\t\t\t\t.where(\"content_taxonomies.collection\", \"=\", collection)\n\t\t\t\t\t.where(\"content_taxonomies.entry_id\", \"in\", chunk)\n\t\t\t\t\t.where(\"taxonomies.name\", \"=\", taxonomyName)\n\t\t\t\t\t// Match the order getAllTermsForEntries (the cache primer) uses, so\n\t\t\t\t\t// cache-hit and DB-miss entries in one result are ordered consistently.\n\t\t\t\t\t.orderBy(\"taxonomies.label\", \"asc\");\n\t\t\t\tif (locale !== undefined) query = query.where(\"taxonomies.locale\", \"=\", locale);\n\t\t\t\trows = await query.execute();\n\t\t\t} catch (error) {\n\t\t\t\tif (isMissingTableError(error)) return [...result.entries()];\n\t\t\t\tthrow error;\n\t\t\t}\n\n\t\t\tfor (const row of rows) {\n\t\t\t\tconst term: TaxonomyTerm = {\n\t\t\t\t\tid: row.id,\n\t\t\t\t\tname: row.name,\n\t\t\t\t\tslug: row.slug,\n\t\t\t\t\tlabel: row.label,\n\t\t\t\t\tparentId: row.parent_id ?? undefined,\n\t\t\t\t\tchildren: [],\n\t\t\t\t\tlocale: row.locale,\n\t\t\t\t\ttranslationGroup: row.translation_group,\n\t\t\t\t};\n\t\t\t\tconst terms = result.get(row.entry_id);\n\t\t\t\tif (terms) terms.push(term);\n\t\t\t}\n\t\t}\n\n\t\treturn [...result.entries()];\n\t};\n\n\t// Key on the sorted unique ids. Bound the key length: very large batches\n\t// (rare; they come from collection hydration, already served by the content\n\t// cache) bypass the object cache rather than blow past KV's key limit.\n\tconst idKey = uniqueIds.toSorted().join(\",\");\n\tconst pairs =\n\t\tidKey.length <= 256\n\t\t\t? await cachedQuery({\n\t\t\t\t\tnamespace: [contentNamespace(collection), CacheNamespace.TAXONOMIES],\n\t\t\t\t\tkey: `termsForEntries:${collection}:${taxonomyName}:${locale ?? \"*\"}:${idKey}`,\n\t\t\t\t\tload,\n\t\t\t\t})\n\t\t\t: await load();\n\n\treturn new Map(pairs);\n}\n\n/**\n * Batch-fetch terms for multiple entries across ALL taxonomies in one query.\n * Primes the request-cache for subsequent per-entry calls to `getEntryTerms`.\n */\nexport async function getAllTermsForEntries(\n\tcollection: string,\n\tentryIds: string[],\n\toptions: TaxonomyQueryOptions = {},\n): Promise<Map<string, Record<string, TaxonomyTerm[]>>> {\n\tconst result = new Map<string, Record<string, TaxonomyTerm[]>>();\n\tconst uniqueIds = [...new Set(entryIds)];\n\tfor (const id of uniqueIds) result.set(id, {});\n\tif (uniqueIds.length === 0) return result;\n\n\tconst db = await getDb();\n\tconst locale = resolveLocale(options.locale);\n\tconst applicableTaxonomyNames = await getCollectionTaxonomyNames(collection, { locale });\n\n\tfor (const chunk of chunks(uniqueIds, SQL_BATCH_SIZE)) {\n\t\tlet rows;\n\t\ttry {\n\t\t\tlet query = db\n\t\t\t\t.selectFrom(\"content_taxonomies\")\n\t\t\t\t.innerJoin(\"taxonomies\", \"taxonomies.translation_group\", \"content_taxonomies.taxonomy_id\")\n\t\t\t\t.select([\n\t\t\t\t\t\"content_taxonomies.entry_id\",\n\t\t\t\t\t\"taxonomies.id\",\n\t\t\t\t\t\"taxonomies.name\",\n\t\t\t\t\t\"taxonomies.slug\",\n\t\t\t\t\t\"taxonomies.label\",\n\t\t\t\t\t\"taxonomies.parent_id\",\n\t\t\t\t\t\"taxonomies.locale\",\n\t\t\t\t\t\"taxonomies.translation_group\",\n\t\t\t\t])\n\t\t\t\t.where(\"content_taxonomies.collection\", \"=\", collection)\n\t\t\t\t.where(\"content_taxonomies.entry_id\", \"in\", chunk)\n\t\t\t\t.orderBy(\"taxonomies.label\", \"asc\");\n\t\t\tif (locale !== undefined) query = query.where(\"taxonomies.locale\", \"=\", locale);\n\t\t\trows = await query.execute();\n\t\t} catch (error) {\n\t\t\tif (isMissingTableError(error)) {\n\t\t\t\tfor (const id of uniqueIds) {\n\t\t\t\t\tprimeEntryTermsCache(collection, id, {}, applicableTaxonomyNames, locale);\n\t\t\t\t}\n\t\t\t\treturn result;\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\n\t\tfor (const row of rows) {\n\t\t\tconst term: TaxonomyTerm = {\n\t\t\t\tid: row.id,\n\t\t\t\tname: row.name,\n\t\t\t\tslug: row.slug,\n\t\t\t\tlabel: row.label,\n\t\t\t\tparentId: row.parent_id ?? undefined,\n\t\t\t\tchildren: [],\n\t\t\t\tlocale: row.locale,\n\t\t\t\ttranslationGroup: row.translation_group,\n\t\t\t};\n\t\t\tconst byTaxonomy = result.get(row.entry_id);\n\t\t\tif (!byTaxonomy) continue;\n\t\t\tconst existing = byTaxonomy[row.name];\n\t\t\tif (existing) existing.push(term);\n\t\t\telse byTaxonomy[row.name] = [term];\n\t\t}\n\t}\n\n\tfor (const [entryId, byTaxonomy] of result) {\n\t\tprimeEntryTermsCache(collection, entryId, byTaxonomy, applicableTaxonomyNames, locale);\n\t}\n\n\treturn result;\n}\n\n/**\n * Return the list of taxonomy names applicable to a collection, request-\n * cached so a page render only pays for it once.\n *\n * Returns an empty list when taxonomies haven't been defined yet.\n */\nasync function getCollectionTaxonomyNames(\n\tcollection: string,\n\toptions: TaxonomyQueryOptions,\n): Promise<string[]> {\n\ttry {\n\t\tconst defs = await getTaxonomyDefs(options);\n\t\treturn defs.filter((d) => d.collections.includes(collection)).map((d) => d.name);\n\t} catch (error) {\n\t\tif (isMissingTableError(error)) return [];\n\t\tthrow error;\n\t}\n}\n\n/**\n * Pre-populate the request-cache for every getEntryTerms call-shape that\n * could hit this entry:\n *\n * getEntryTerms(collection, entryId) -> key `terms:C:E:*`\n * getEntryTerms(collection, entryId, \"tag\") -> key `terms:C:E:tag`\n * getEntryTerms(collection, entryId, \"category\") -> key `terms:C:E:category`\n * ...one per taxonomy that applies to this collection\n *\n * Taxonomies with no rows on this entry are seeded with `[]` so legacy\n * callers short-circuit to the cached empty array instead of re-querying.\n */\nfunction primeEntryTermsCache(\n\tcollection: string,\n\tentryId: string,\n\tbyTaxonomy: Record<string, TaxonomyTerm[]>,\n\tapplicableTaxonomyNames: string[],\n\tlocale: string | undefined,\n): void {\n\tconst localeKey = locale ?? \"*\";\n\tfor (const name of applicableTaxonomyNames) {\n\t\tsetRequestCacheEntry(\n\t\t\t`terms:${collection}:${entryId}:${name}:${localeKey}`,\n\t\t\tbyTaxonomy[name] ?? [],\n\t\t);\n\t}\n\tfor (const [name, terms] of Object.entries(byTaxonomy)) {\n\t\tsetRequestCacheEntry(`terms:${collection}:${entryId}:${name}:${localeKey}`, terms);\n\t}\n\tconst allTerms = Object.values(byTaxonomy).flat();\n\tsetRequestCacheEntry(`terms:${collection}:${entryId}:*:${localeKey}`, allTerms);\n}\n\n/**\n * Prime the per-entry request cache from terms that were folded into the\n * content query (query.ts `hydrateEntryTerms` fast path), so subsequent\n * `getEntryTerms` calls in the same render hit the cache instead of issuing an\n * N+1 query. Seeds the wildcard key and one key per taxonomy present on the\n * entry — purely from the folded data, with no DB lookup.\n *\n * Unlike `getAllTermsForEntries`, this deliberately does NOT seed `[]` for\n * taxonomies that apply to the collection but have no rows on the entry: doing\n * so would require a `getTaxonomyDefs` query, adding a round trip to every fold\n * render to serve the rarer `getEntryTerms(id, absentTaxonomy)` case from cache.\n * That call simply falls through to its own cached query. Keeping the key shape\n * here (rather than in query.ts) prevents the two from drifting.\n */\nexport function primeFoldedEntryTerms(\n\tcollection: string,\n\tperEntry: Array<{ entryId: string; byTaxonomy: Record<string, TaxonomyTerm[]> }>,\n\toptions: TaxonomyQueryOptions = {},\n): void {\n\tif (perEntry.length === 0) return;\n\tconst locale = resolveLocale(options.locale);\n\tfor (const { entryId, byTaxonomy } of perEntry) {\n\t\tprimeEntryTermsCache(collection, entryId, byTaxonomy, [], locale);\n\t}\n}\n\n/**\n * Get entries by term. Both the lookup (term slug in the active locale) and\n * the content query respect the active locale.\n */\nexport async function getEntriesByTerm(\n\tcollection: string,\n\ttaxonomyName: string,\n\ttermSlug: string,\n\toptions: TaxonomyQueryOptions = {},\n): Promise<Array<{ id: string; data: Record<string, unknown> }>> {\n\tconst { getEmDashCollection } = await import(\"../query.js\");\n\n\tconst queryOptions: Record<string, unknown> = {\n\t\twhere: { [taxonomyName]: termSlug },\n\t};\n\tif (options.locale !== undefined) queryOptions.locale = options.locale;\n\tconst { entries } = await getEmDashCollection(collection, queryOptions);\n\treturn entries;\n}\n\nfunction rowToTaxonomyDef(row: {\n\tid: string;\n\tname: string;\n\tlabel: string;\n\tlabel_singular: string | null;\n\thierarchical: number;\n\tcollections: string | null;\n\tlocale: string;\n\ttranslation_group: string | null;\n}): TaxonomyDef {\n\treturn {\n\t\tid: row.id,\n\t\tname: row.name,\n\t\tlabel: row.label,\n\t\tlabelSingular: row.label_singular ?? undefined,\n\t\thierarchical: row.hierarchical === 1,\n\t\tcollections: row.collections ? JSON.parse(row.collections) : [],\n\t\tlocale: row.locale,\n\t\ttranslationGroup: row.translation_group,\n\t};\n}\n\n/**\n * Build tree structure from flat terms\n */\nfunction buildTree(flatTerms: TaxonomyTermRow[], counts: Map<string, number>): TaxonomyTerm[] {\n\t// parent_id holds the parent's translation_group, so link children by it.\n\t// Key by (locale, group): a child's parent lives in the same locale, and an\n\t// unfiltered set mixes locales whose translated siblings share a group —\n\t// keying by group alone would collide and misattach children across locales.\n\tconst byLocaleGroup = new Map<string, TaxonomyTerm>();\n\tconst nodes: TaxonomyTerm[] = [];\n\tconst roots: TaxonomyTerm[] = [];\n\n\tfor (const term of flatTerms) {\n\t\tconst node: TaxonomyTerm = {\n\t\t\tid: term.id,\n\t\t\tname: term.name,\n\t\t\tslug: term.slug,\n\t\t\tlabel: term.label,\n\t\t\tparentId: term.parent_id ?? undefined,\n\t\t\tdescription: term.data ? JSON.parse(term.data).description : undefined,\n\t\t\tchildren: [],\n\t\t\tcount: counts.get(term.translation_group ?? term.id) ?? 0,\n\t\t\tlocale: term.locale,\n\t\t\ttranslationGroup: term.translation_group,\n\t\t};\n\t\tbyLocaleGroup.set(`${term.locale}::${term.translation_group ?? term.id}`, node);\n\t\tnodes.push(node);\n\t}\n\n\tfor (const node of nodes) {\n\t\tconst parent = node.parentId\n\t\t\t? byLocaleGroup.get(`${node.locale}::${node.parentId}`)\n\t\t\t: undefined;\n\t\tif (parent) {\n\t\t\tparent.children.push(node);\n\t\t} else {\n\t\t\troots.push(node);\n\t\t}\n\t}\n\n\treturn roots;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCA,SAAgB,sBAA4B;AAC3C,gCAA+B;;AAiChC,MAAM,0BAA0B,OAAO,IAAI,uBAAuB;AAClE,MAAM,oBAAoB;AAC1B,MAAM,aAEJ,kBAAkB,mCACZ;CACN,MAAM,IAAwB;EAAE,SAAS;EAAG,uBAAO,IAAI,KAAK;EAAE;AAC9D,mBAAkB,2BAA2B;AAC7C,QAAO;IACJ;;;;;;;AAQL,SAAgB,8BAAoC;AACnD,YAAW;A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ACZ,UAAU,KAAK,aAAa;GAC5B,aAAa,KAAK,OAAO,KAAK,MAAM,KAAK,KAAK,CAAC,cAAc;GAC7D,UAAU,EAAE;GACZ,OAAO,OAAO,IAAI,KAAK,qBAAqB,KAAK,GAAG,IAAI;GACxD,QAAQ,KAAK;GACb,kBAAkB,KAAK;GACvB;AACD,gBAAc,IAAI,GAAG,KAAK,OAAO,IAAI,KAAK,qBAAqB,KAAK,MAAM,KAAK;AAC/E,QAAM,KAAK,KAAK;;AAGjB,MAAK,MAAM,QAAQ,OAAO;EACzB,MAAM,SAAS,KAAK,WACjB,cAAc,IAAI,GAAG,KAAK,OAAO,IAAI,KAAK,WAAW,GACrD;AACH,MAAI,OACH,QAAO,SAAS,KAAK,KAAK;MAE1B,OAAM,KAAK,KAAK;;AAIlB,QAAO"}
|
|
@@ -4,9 +4,9 @@ import "./base64-CmWvODNW.mjs";
|
|
|
4
4
|
import "./types-CuW0zWDA.mjs";
|
|
5
5
|
import { n as chunks, t as SQL_BATCH_SIZE } from "./chunks-B2isWQhr.mjs";
|
|
6
6
|
import { n as isMissingTableError } from "./db-errors-CK46D-ly.mjs";
|
|
7
|
-
import "./content-refresh-
|
|
7
|
+
import "./content-refresh-Br4gMzh8.mjs";
|
|
8
8
|
import "./fts-manager-BbFaF_V8.mjs";
|
|
9
|
-
import { n as SchemaRegistry } from "./registry-
|
|
9
|
+
import { n as SchemaRegistry } from "./registry-B57vp_X9.mjs";
|
|
10
10
|
import { n as generateZodSchema } from "./zod-generator-CacrR-i8.mjs";
|
|
11
11
|
import { sql } from "kysely";
|
|
12
12
|
|
|
@@ -145,4 +145,4 @@ async function validateContentData(db, collection, data, options = {}) {
|
|
|
145
145
|
|
|
146
146
|
//#endregion
|
|
147
147
|
export { validateContentData };
|
|
148
|
-
//# sourceMappingURL=validation-
|
|
148
|
+
//# sourceMappingURL=validation-0l8-RYj4.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validation-c8WjhH8z.mjs","names":[],"sources":["../src/api/handlers/validation.ts"],"sourcesContent":["/**\n * Field-level validation for content create / update.\n *\n * Wires the existing `generateZodSchema()` pipeline (`schema/zod-generator.ts`)\n * into the handler boundary so REST and MCP both get the same enforcement:\n *\n * - required fields must be present and non-empty\n * - select / multiSelect values must match the configured options\n * - reference fields must resolve to a real, non-trashed target\n *\n * Errors surface as `{ code: \"VALIDATION_ERROR\", message }` with all\n * offending fields listed in one message so callers can fix everything in\n * a single round trip.\n */\n\nimport { sql, type Kysely } from \"kysely\";\n\nimport type { Database } from \"../../database/types.js\";\nimport { validateIdentifier } from \"../../database/validate.js\";\nimport { SchemaRegistry } from \"../../schema/registry.js\";\nimport type { Field } from \"../../schema/types.js\";\nimport { generateZodSchema } from \"../../schema/zod-generator.js\";\nimport { chunks, SQL_BATCH_SIZE } from \"../../utils/chunks.js\";\nimport { isMissingTableError } from \"../../utils/db-errors.js\";\n\ntype ValidationResult =\n\t| { ok: true }\n\t| { ok: false; error: { code: \"VALIDATION_ERROR\" | \"COLLECTION_NOT_FOUND\"; message: string } };\n\n/** Treat `undefined`, `null`, and `\"\"` as \"not set\". */\nfunction isMissing(value: unknown): boolean {\n\treturn value === undefined || value === null || value === \"\";\n}\n\n/**\n * Resolve the target collection slug for a reference field.\n *\n * Schema-defined reference fields (the static `reference()` factory in\n * `fields/reference.ts`) put the target in `options.collection`. The MCP\n * `schema_create_field` tool also puts it there. Tests and some admin paths\n * stash it inside `validation.collection` directly; we accept both.\n */\nfunction getReferenceTargetCollection(field: Field): string | undefined {\n\tconst fromOptions = field.options?.collection;\n\tif (typeof fromOptions === \"string\" && fromOptions.length > 0) return fromOptions;\n\tconst validation = field.validation;\n\tif (validation && \"collection\" in validation) {\n\t\tconst fromValidation: unknown = (validation as { collection?: unknown }).collection;\n\t\tif (typeof fromValidation === \"string\" && fromValidation.length > 0) return fromValidation;\n\t}\n\treturn undefined;\n}\n\n/**\n * Format a Zod issue path into a human-readable field reference, e.g.\n * `tags`, `tags.1`, `image.alt`.\n */\nfunction formatIssuePath(path: ReadonlyArray<PropertyKey>): string {\n\tif (path.length === 0) return \"(root)\";\n\treturn path.map((seg) => String(seg)).join(\".\");\n}\n\n/**\n * Validate `data` against the collection's field definitions.\n *\n * `partial: true` switches Zod into partial mode so updates can include\n * only the fields being changed without tripping required-field errors on\n * fields the caller didn't touch. Required fields that ARE present in\n * partial-mode data still get the empty-string check below.\n */\nexport async function validateContentData(\n\tdb: Kysely<Database>,\n\tcollection: string,\n\tdata: Record<string, unknown>,\n\toptions: { partial?: boolean } = {},\n): Promise<ValidationResult> {\n\tconst registry = new SchemaRegistry(db);\n\tconst collectionWithFields = await registry.getCollectionWithFields(collection);\n\tif (!collectionWithFields) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: {\n\t\t\t\tcode: \"COLLECTION_NOT_FOUND\",\n\t\t\t\tmessage: `Collection '${collection}' not found`,\n\t\t\t},\n\t\t};\n\t}\n\n\tconst issues: string[] = [];\n\n\t// Detect unknown keys explicitly so callers get a useful error rather\n\t// than silently dropped data. Leading-underscore keys (e.g. `_slug`,\n\t// `_rev`) are reserved for internal handler/runtime use and aren't real\n\t// fields; skip them.\n\tconst knownFields = new Set(collectionWithFields.fields.map((f) => f.slug));\n\tfor (const key of Object.keys(data)) {\n\t\tif (key.startsWith(\"_\")) continue;\n\t\tif (!knownFields.has(key)) {\n\t\t\tissues.push(`${key}: unknown field on collection '${collection}'`);\n\t\t}\n\t}\n\n\t// Zod handles type, enum, length and missing-required (in non-partial\n\t// mode) checks. Empty-string handling for required string fields is\n\t// done as a separate pass below since Zod's `z.string()` accepts \"\".\n\tconst baseSchema = generateZodSchema(collectionWithFields);\n\tconst schema = options.partial ? baseSchema.partial() : baseSchema;\n\tconst parsed = schema.safeParse(data);\n\tif (!parsed.success) {\n\t\tfor (const issue of parsed.error.issues) {\n\t\t\tissues.push(`${formatIssuePath(issue.path)}: ${issue.message}`);\n\t\t}\n\t}\n\n\t// Empty-string-on-required check. In create mode (partial=false) Zod\n\t// already catches missing/null for required fields, but `z.string()`\n\t// happily accepts \"\". In update mode (partial=true) the field is only\n\t// checked if it's present in `data`.\n\tfor (const field of collectionWithFields.fields) {\n\t\tif (!field.required) continue;\n\t\tconst present = Object.hasOwn(data, field.slug);\n\t\tif (options.partial && !present) continue;\n\t\tif (data[field.slug] === \"\") {\n\t\t\tissues.push(`${field.slug}: required (empty value not allowed)`);\n\t\t}\n\t}\n\n\t// Reference target existence. Only check fields that:\n\t// - have a value (non-missing) in `data`\n\t// - have a resolvable target collection\n\t// - in partial mode: are present in `data`\n\t// Batch one IN-query per target collection to keep round-trips low.\n\tconst refsByTarget = new Map<string, { field: string; id: string }[]>();\n\tfor (const field of collectionWithFields.fields) {\n\t\tif (field.type !== \"reference\") continue;\n\t\tif (options.partial && !Object.hasOwn(data, field.slug)) continue;\n\t\tconst value = data[field.slug];\n\t\tif (isMissing(value)) continue;\n\t\tif (typeof value !== \"string\") continue; // Zod will have flagged this already\n\t\tconst target = getReferenceTargetCollection(field);\n\t\tif (!target) continue;\n\t\tconst list = refsByTarget.get(target) ?? [];\n\t\tlist.push({ field: field.slug, id: value });\n\t\trefsByTarget.set(target, list);\n\t}\n\n\tfor (const [target, refs] of refsByTarget) {\n\t\t// Validate the target collection slug before interpolating into raw\n\t\t// SQL — defense-in-depth even though slugs are already validated at\n\t\t// schema-create time.\n\t\ttry {\n\t\t\tvalidateIdentifier(target, \"reference target collection\");\n\t\t} catch {\n\t\t\tfor (const ref of refs) {\n\t\t\t\tissues.push(`${ref.field}: invalid reference target collection '${target}'`);\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst ids = [...new Set(refs.map((r) => r.id))];\n\t\tconst tableName = `ec_${target}`;\n\n\t\t// Chunk the IN clause to stay below D1's bind-parameter limit. One\n\t\t// reference per request is the common case today; chunking makes the\n\t\t// helper safe if a future multiSelect-of-references is added.\n\t\tconst found = new Set<string>();\n\t\tlet targetTableMissing = false;\n\t\tfor (const idChunk of chunks(ids, SQL_BATCH_SIZE)) {\n\t\t\ttry {\n\t\t\t\tconst rows = await sql<{ id: string }>`\n\t\t\t\t\tSELECT id FROM ${sql.ref(tableName)}\n\t\t\t\t\tWHERE id IN (${sql.join(idChunk)})\n\t\t\t\t\tAND deleted_at IS NULL\n\t\t\t\t`.execute(db);\n\t\t\t\tfor (const row of rows.rows) {\n\t\t\t\t\tfound.add(row.id);\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\t// Missing table = the target collection table doesn't exist\n\t\t\t\t// (orphan reference). Treat all those references as missing.\n\t\t\t\t// Any other DB error (permissions, connection, syntax) must\n\t\t\t\t// propagate — silently dropping data integrity errors as\n\t\t\t\t// \"not found\" is exactly the bug F5 fixes.\n\t\t\t\tif (isMissingTableError(error)) {\n\t\t\t\t\ttargetTableMissing = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\t\tif (targetTableMissing) {\n\t\t\tfor (const ref of refs) {\n\t\t\t\tissues.push(`${ref.field}: target '${ref.id}' not found in collection '${target}'`);\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tfor (const ref of refs) {\n\t\t\tif (!found.has(ref.id)) {\n\t\t\t\tissues.push(`${ref.field}: target '${ref.id}' not found in collection '${target}'`);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (issues.length === 0) return { ok: true };\n\treturn {\n\t\tok: false,\n\t\terror: {\n\t\t\tcode: \"VALIDATION_ERROR\",\n\t\t\tmessage: issues.join(\"; \"),\n\t\t},\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BA,SAAS,UAAU,OAAyB;AAC3C,QAAO,UAAU,UAAa,UAAU,QAAQ,UAAU;;;;;;;;;;AAW3D,SAAS,6BAA6B,OAAkC;CACvE,MAAM,cAAc,MAAM,SAAS;AACnC,KAAI,OAAO,gBAAgB,YAAY,YAAY,SAAS,EAAG,QAAO;CACtE,MAAM,a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O,GAAG;AAEpF;;AAED,OAAK,MAAM,OAAO,KACjB,KAAI,CAAC,MAAM,IAAI,IAAI,GAAG,CACrB,QAAO,KAAK,GAAG,IAAI,MAAM,YAAY,IAAI,GAAG,6BAA6B,OAAO,GAAG;;AAKtF,KAAI,OAAO,WAAW,EAAG,QAAO,EAAE,IAAI,MAAM;AAC5C,QAAO;EACN,IAAI;EACJ,OAAO;GACN,MAAM;GACN,SAAS,OAAO,KAAK,KAAK;GAC1B;EACD"}
|
|
1
|
+
{"version":3,"file":"validation-0l8-RYj4.mjs","names":[],"sources":["../src/api/handlers/validation.ts"],"sourcesContent":["/**\n * Field-level validation for content create / update.\n *\n * Wires the existing `generateZodSchema()` pipeline (`schema/zod-generator.ts`)\n * into the handler boundary so REST and MCP both get the same enforcement:\n *\n * - required fields must be present and non-empty\n * - select / multiSelect values must match the configured options\n * - reference fields must resolve to a real, non-trashed target\n *\n * Errors surface as `{ code: \"VALIDATION_ERROR\", message }` with all\n * offending fields listed in one message so callers can fix everything in\n * a single round trip.\n */\n\nimport { sql, type Kysely } from \"kysely\";\n\nimport type { Database } from \"../../database/types.js\";\nimport { validateIdentifier } from \"../../database/validate.js\";\nimport { SchemaRegistry } from \"../../schema/registry.js\";\nimport type { Field } from \"../../schema/types.js\";\nimport { generateZodSchema } from \"../../schema/zod-generator.js\";\nimport { chunks, SQL_BATCH_SIZE } from \"../../utils/chunks.js\";\nimport { isMissingTableError } from \"../../utils/db-errors.js\";\n\ntype ValidationResult =\n\t| { ok: true }\n\t| { ok: false; error: { code: \"VALIDATION_ERROR\" | \"COLLECTION_NOT_FOUND\"; message: string } };\n\n/** Treat `undefined`, `null`, and `\"\"` as \"not set\". */\nfunction isMissing(value: unknown): boolean {\n\treturn value === undefined || value === null || value === \"\";\n}\n\n/**\n * Resolve the target collection slug for a reference field.\n *\n * Schema-defined reference fields (the static `reference()` factory in\n * `fields/reference.ts`) put the target in `options.collection`. The MCP\n * `schema_create_field` tool also puts it there. Tests and some admin paths\n * stash it inside `validation.collection` directly; we accept both.\n */\nfunction getReferenceTargetCollection(field: Field): string | undefined {\n\tconst fromOptions = field.options?.collection;\n\tif (typeof fromOptions === \"string\" && fromOptions.length > 0) return fromOptions;\n\tconst validation = field.validation;\n\tif (validation && \"collection\" in validation) {\n\t\tconst fromValidation: unknown = (validation as { collection?: unknown }).collection;\n\t\tif (typeof fromValidation === \"string\" && fromValidation.length > 0) return fromValidation;\n\t}\n\treturn undefined;\n}\n\n/**\n * Format a Zod issue path into a human-readable field reference, e.g.\n * `tags`, `tags.1`, `image.alt`.\n */\nfunction formatIssuePath(path: ReadonlyArray<PropertyKey>): string {\n\tif (path.length === 0) return \"(root)\";\n\treturn path.map((seg) => String(seg)).join(\".\");\n}\n\n/**\n * Validate `data` against the collection's field definitions.\n *\n * `partial: true` switches Zod into partial mode so updates can include\n * only the fields being changed without tripping required-field errors on\n * fields the caller didn't touch. Required fields that ARE present in\n * partial-mode data still get the empty-string check below.\n */\nexport async function validateContentData(\n\tdb: Kysely<Database>,\n\tcollection: string,\n\tdata: Record<string, unknown>,\n\toptions: { partial?: boolean } = {},\n): Promise<ValidationResult> {\n\tconst registry = new SchemaRegistry(db);\n\tconst collectionWithFields = await registry.getCollectionWithFields(collection);\n\tif (!collectionWithFields) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: {\n\t\t\t\tcode: \"COLLECTION_NOT_FOUND\",\n\t\t\t\tmessage: `Collection '${collection}' not found`,\n\t\t\t},\n\t\t};\n\t}\n\n\tconst issues: string[] = [];\n\n\t// Detect unknown keys explicitly so callers get a useful error rather\n\t// than silently dropped data. Leading-underscore keys (e.g. `_slug`,\n\t// `_rev`) are reserved for internal handler/runtime use and aren't real\n\t// fields; skip them.\n\tconst knownFields = new Set(collectionWithFields.fields.map((f) => f.slug));\n\tfor (const key of Object.keys(data)) {\n\t\tif (key.startsWith(\"_\")) continue;\n\t\tif (!knownFields.has(key)) {\n\t\t\tissues.push(`${key}: unknown field on collection '${collection}'`);\n\t\t}\n\t}\n\n\t// Zod handles type, enum, length and missing-required (in non-partial\n\t// mode) checks. Empty-string handling for required string fields is\n\t// done as a separate pass below since Zod's `z.string()` accepts \"\".\n\tconst baseSchema = generateZodSchema(collectionWithFields);\n\tconst schema = options.partial ? baseSchema.partial() : baseSchema;\n\tconst parsed = schema.safeParse(data);\n\tif (!parsed.success) {\n\t\tfor (const issue of parsed.error.issues) {\n\t\t\tissues.push(`${formatIssuePath(issue.path)}: ${issue.message}`);\n\t\t}\n\t}\n\n\t// Empty-string-on-required check. In create mode (partial=false) Zod\n\t// already catches missing/null for required fields, but `z.string()`\n\t// happily accepts \"\". In update mode (partial=true) the field is only\n\t// checked if it's present in `data`.\n\tfor (const field of collectionWithFields.fields) {\n\t\tif (!field.required) continue;\n\t\tconst present = Object.hasOwn(data, field.slug);\n\t\tif (options.partial && !present) continue;\n\t\tif (data[field.slug] === \"\") {\n\t\t\tissues.push(`${field.slug}: required (empty value not allowed)`);\n\t\t}\n\t}\n\n\t// Reference target existence. Only check fields that:\n\t// - have a value (non-missing) in `data`\n\t// - have a resolvable target collection\n\t// - in partial mode: are present in `data`\n\t// Batch one IN-query per target collection to keep round-trips low.\n\tconst refsByTarget = new Map<string, { field: string; id: string }[]>();\n\tfor (const field of collectionWithFields.fields) {\n\t\tif (field.type !== \"reference\") continue;\n\t\tif (options.partial && !Object.hasOwn(data, field.slug)) continue;\n\t\tconst value = data[field.slug];\n\t\tif (isMissing(value)) continue;\n\t\tif (typeof value !== \"string\") continue; // Zod will have flagged this already\n\t\tconst target = getReferenceTargetCollection(field);\n\t\tif (!target) continue;\n\t\tconst list = refsByTarget.get(target) ?? [];\n\t\tlist.push({ field: field.slug, id: value });\n\t\trefsByTarget.set(target, list);\n\t}\n\n\tfor (const [target, refs] of refsByTarget) {\n\t\t// Validate the target collection slug before interpolating into raw\n\t\t// SQL — defense-in-depth even though slugs are already validated at\n\t\t// schema-create time.\n\t\ttry {\n\t\t\tvalidateIdentifier(target, \"reference target collection\");\n\t\t} catch {\n\t\t\tfor (const ref of refs) {\n\t\t\t\tissues.push(`${ref.field}: invalid reference target collection '${target}'`);\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst ids = [...new Set(refs.map((r) => r.id))];\n\t\tconst tableName = `ec_${target}`;\n\n\t\t// Chunk the IN clause to stay below D1's bind-parameter limit. One\n\t\t// reference per request is the common case today; chunking makes the\n\t\t// helper safe if a future multiSelect-of-references is added.\n\t\tconst found = new Set<string>();\n\t\tlet targetTableMissing = false;\n\t\tfor (const idChunk of chunks(ids, SQL_BATCH_SIZE)) {\n\t\t\ttry {\n\t\t\t\tconst rows = await sql<{ id: string }>`\n\t\t\t\t\tSELECT id FROM ${sql.ref(tableName)}\n\t\t\t\t\tWHERE id IN (${sql.join(idChunk)})\n\t\t\t\t\tAND deleted_at IS NULL\n\t\t\t\t`.execute(db);\n\t\t\t\tfor (const row of rows.rows) {\n\t\t\t\t\tfound.add(row.id);\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\t// Missing table = the target collection table doesn't exist\n\t\t\t\t// (orphan reference). Treat all those references as missing.\n\t\t\t\t// Any other DB error (permissions, connection, syntax) must\n\t\t\t\t// propagate — silently dropping data integrity errors as\n\t\t\t\t// \"not found\" is exactly the bug F5 fixes.\n\t\t\t\tif (isMissingTableError(error)) {\n\t\t\t\t\ttargetTableMissing = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\t\tif (targetTableMissing) {\n\t\t\tfor (const ref of refs) {\n\t\t\t\tissues.push(`${ref.field}: target '${ref.id}' not found in collection '${target}'`);\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tfor (const ref of refs) {\n\t\t\tif (!found.has(ref.id)) {\n\t\t\t\tissues.push(`${ref.field}: target '${ref.id}' not found in collection '${target}'`);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (issues.length === 0) return { ok: true };\n\treturn {\n\t\tok: false,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,GAAmB;sBACpB,IAAI,IAAI,UAAU,CAAC;oBACrB,IAAI,KAAK,QAAQ,CAAC;;MAEhC,QAAQ,GAAG;AACb,QAAK,MAAM,OAAO,KAAK,KACtB,OAAM,IAAI,IAAI,GAAG;WAEV,OAAO;AAMf,OAAI,oBAAoB,MAAM,EAAE;AAC/B,yBAAqB;AACrB;;AAED,SAAM;;AAGR,MAAI,oBAAoB;AACvB,QAAK,MAAM,OAAO,KACjB,QAAO,KAAK,GAAG,IAAI,MAAM,YAAY,IAAI,GAAG,6BAA6B,OAAO,GAAG;AAEpF;;AAED,OAAK,MAAM,OAAO,KACjB,KAAI,CAAC,MAAM,IAAI,IAAI,GAAG,CACrB,QAAO,KAAK,GAAG,IAAI,MAAM,YAAY,IAAI,GAAG,6BAA6B,OAAO,GAAG;;AAKtF,KAAI,OAAO,WAAW,EAAG,QAAO,EAAE,IAAI,MAAM;AAC5C,QAAO;EACN,IAAI;EACJ,OAAO;GACN,MAAM;GACN,SAAS,OAAO,KAAK,KAAK;GAC1B;EACD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"version-
|
|
1
|
+
{"version":3,"file":"version-qmeO1XZY.mjs","names":[],"sources":["../src/version.ts"],"sourcesContent":["/**\n * Build-time version constants, replaced by tsdown/Vite `define`.\n * Falls back to \"dev\" when running uncompiled (tests, dev).\n */\n\ndeclare const __EMDASH_VERSION__: string;\ndeclare const __EMDASH_COMMIT__: string;\n\nexport const VERSION: string =\n\ttypeof __EMDASH_VERSION__ !== \"undefined\" ? __EMDASH_VERSION__ : \"dev\";\n\nexport const COMMIT: string = typeof __EMDASH_COMMIT__ !== \"undefined\" ? __EMDASH_COMMIT__ : \"dev\";\n"],"mappings":";AAQA,MAAa;AAGb,MAAa"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { t as TaxonomyRepository } from "./taxonomy-BxGxZZdu.mjs";
|
|
2
2
|
import { i as resolveLocaleChain } from "./resolve-DR3wqMTy.mjs";
|
|
3
|
-
import { u as invalidateTermCache } from "./taxonomies-
|
|
3
|
+
import { u as invalidateTermCache } from "./taxonomies-kH9ABDUF.mjs";
|
|
4
4
|
|
|
5
5
|
//#region src/import/wxr-taxonomies.ts
|
|
6
6
|
/**
|
|
@@ -422,4 +422,4 @@ async function mirrorTermsToLocales(db, plan, postLocales, canonicalLocale) {
|
|
|
422
422
|
|
|
423
423
|
//#endregion
|
|
424
424
|
export { preImportWxrTaxonomies as a, mirrorTermsToLocales as i, isWxrTaxonomyConflictError as n, setPostTermAssignmentsReplacing as o, loadTaxonomyPlanFromDb as r, attachPostTaxonomies as t };
|
|
425
|
-
//# sourceMappingURL=wxr-taxonomies-
|
|
425
|
+
//# sourceMappingURL=wxr-taxonomies-CNFcsNCr.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"wxr-taxonomies-BC3OYpvx.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\n\tlet attached = 0;\n\tfor (const [, termIds] of resolved) {\n\t\tfor (const termId of termIds) {\n\t\t\tconst wrote = await attachToEntryCountingInserts(db, repo, plan, collection, entryId, termId);\n\t\t\tif (wrote) attached++;\n\t\t}\n\t}\n\treturn attached;\n}\n\n/**\n * Replace assignments per-taxonomy from a parsed WXR post. Used for\n * translations: WPML's \"Translate Independently\" mode lets translators\n * override term assignments per-taxonomy, not per-post. A translation that\n * overrides `category` shouldn't lose its inherited `tag` or `genre`. We\n * only call `setTermsForEntry(name, ids)` for taxonomies where the\n * translation actually resolved at least one term -- taxonomies with no\n * resolvable+permitted terms are left alone so inherited rows from\n * `copyEntryTerms` stay intact.\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 * Wrapper around `TaxonomyRepository.attachToEntry` that returns whether\n * an actual row was inserted (vs. silently skipped by the `ON CONFLICT DO\n * NOTHING` branch). Lets the importer's `assignments` counter reflect real\n * writes rather than re-import no-ops.\n *\n * Best-effort: we check pivot existence first, then call `attachToEntry`.\n * A concurrent insert between the check and the attach would make us\n * report `false` while a row was in fact inserted -- the count is for\n * summary display only, never correctness.\n */\nasync function attachToEntryCountingInserts(\n\tdb: Kysely<Database>,\n\trepo: TaxonomyRepository,\n\tplan: TaxonomyImportPlan,\n\tcollection: string,\n\tentryId: string,\n\ttermId: string,\n): Promise<boolean> {\n\tconst group = await termTranslationGroup(repo, plan, termId);\n\tif (!group) return false;\n\n\tconst existing = await db\n\t\t.selectFrom(\"content_taxonomies\")\n\t\t.select(\"collection\")\n\t\t.where(\"collection\", \"=\", collection)\n\t\t.where(\"entry_id\", \"=\", entryId)\n\t\t.where(\"taxonomy_id\", \"=\", group)\n\t\t.executeTakeFirst();\n\tif (existing) return false;\n\n\tawait repo.attachToEntry(collection, entryId, termId);\n\treturn true;\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\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M,IAAI,yBACT,wBAAwB,aAAa,GAAG,KAAK,4BAA4B,OAAO,yGAChF,EAAE,OAAO,OAAO,CAChB;AAEF,QAAI,OAAO,qBAAqB,eAC/B,OAAM,IAAI,yBACT,wBAAwB,aAAa,GAAG,KAAK,4BAA4B,OAAO,mFAChF,EAAE,OAAO,OAAO,CAChB;AAEF,YAAQ,KACP,mDAAmD,aAAa,GAAG,KAAK,eAAe,OAAO,qCAC9F"}
|
|
1
|
+
{"version":3,"file":"wxr-taxonomies-CNFcsNCr.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\n\tlet attached = 0;\n\tfor (const [, termIds] of resolved) {\n\t\tfor (const termId of termIds) {\n\t\t\tconst wrote = await attachToEntryCountingInserts(db, repo, plan, collection, entryId, termId);\n\t\t\tif (wrote) attached++;\n\t\t}\n\t}\n\treturn attached;\n}\n\n/**\n * Replace assignments per-taxonomy from a parsed WXR post. Used for\n * translations: WPML's \"Translate Independently\" mode lets translators\n * override term assignments per-taxonomy, not per-post. A translation that\n * overrides `category` shouldn't lose its inherited `tag` or `genre`. We\n * only call `setTermsForEntry(name, ids)` for taxonomies where the\n * translation actually resolved at least one term -- taxonomies with no\n * resolvable+permitted terms are left alone so inherited rows from\n * `copyEntryTerms` stay intact.\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 * Wrapper around `TaxonomyRepository.attachToEntry` that returns whether\n * an actual row was inserted (vs. silently skipped by the `ON CONFLICT DO\n * NOTHING` branch). Lets the importer's `assignments` counter reflect real\n * writes rather than re-import no-ops.\n *\n * Best-effort: we check pivot existence first, then call `attachToEntry`.\n * A concurrent insert between the check and the attach would make us\n * report `false` while a row was in fact inserted -- the count is for\n * summary display only, never correctness.\n */\nasync function attachToEntryCountingInserts(\n\tdb: Kysely<Database>,\n\trepo: TaxonomyRepository,\n\tplan: TaxonomyImportPlan,\n\tcollection: string,\n\tentryId: string,\n\ttermId: string,\n): Promise<boolean> {\n\tconst group = await termTranslationGroup(repo, plan, termId);\n\tif (!group) return false;\n\n\tconst existing = await db\n\t\t.selectFrom(\"content_taxonomies\")\n\t\t.select(\"collection\")\n\t\t.where(\"collection\", \"=\", collection)\n\t\t.where(\"entry_id\", \"=\", entryId)\n\t\t.where(\"taxonomy_id\", \"=\", group)\n\t\t.executeTakeFirst();\n\tif (existing) return false;\n\n\tawait repo.attachToEntry(collection, entryId, termId);\n\treturn true;\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":";;;;;;;;;;;;;;;;AA8CA,IAAa,2BAAb,cAA8C,MAAM;CACnD,AAAS;CACT,YAAY,eAAuB,SAA+B;AACjE,QAAM,eAAe,QAAQ;AAC7B,OAAK,OAAO;AACZ,OAAK,gBAAgB;;;AAIvB,SAAgB,2BAA2B,OAAmD;AAC7F,QAAO,iBAAi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KACP,mDAAmD,aAAa,GAAG,KAAK,eAAe,OAAO,qCAC9F"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "emdash",
|
|
3
|
-
"version": "0.28.
|
|
3
|
+
"version": "0.28.1",
|
|
4
4
|
"description": "Astro-native CMS with WordPress migration support",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.mjs",
|
|
@@ -230,9 +230,9 @@
|
|
|
230
230
|
"upng-js": "^2.1.0",
|
|
231
231
|
"zod": "^4.4.1",
|
|
232
232
|
"@atcute/client": "^5.0.0",
|
|
233
|
-
"@emdash-cms/admin": "0.28.
|
|
234
|
-
"@emdash-cms/auth": "0.28.
|
|
235
|
-
"@emdash-cms/gutenberg-to-portable-text": "0.28.
|
|
233
|
+
"@emdash-cms/admin": "0.28.1",
|
|
234
|
+
"@emdash-cms/auth": "0.28.1",
|
|
235
|
+
"@emdash-cms/gutenberg-to-portable-text": "0.28.1",
|
|
236
236
|
"@emdash-cms/plugin-types": "0.1.0",
|
|
237
237
|
"@emdash-cms/registry-client": "0.3.2"
|
|
238
238
|
},
|
|
@@ -267,7 +267,7 @@
|
|
|
267
267
|
"vite": "^6.0.0",
|
|
268
268
|
"vitest": "^4.1.5",
|
|
269
269
|
"zod-openapi": "^5.4.6",
|
|
270
|
-
"@emdash-cms/blocks": "0.28.
|
|
270
|
+
"@emdash-cms/blocks": "0.28.1"
|
|
271
271
|
},
|
|
272
272
|
"repository": {
|
|
273
273
|
"type": "git",
|
|
@@ -39,11 +39,16 @@ const handleRequest: APIRoute = async ({ params, request, locals }) => {
|
|
|
39
39
|
|
|
40
40
|
// Public routes skip auth, CSRF, and scope checks entirely
|
|
41
41
|
if (!routeMeta.public) {
|
|
42
|
-
//
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
42
|
+
// Plugin routes are dispatched by name only — the HTTP method never
|
|
43
|
+
// selects a different handler, so a route reached via GET or HEAD runs
|
|
44
|
+
// exactly the same code (and side effects) as one reached via POST.
|
|
45
|
+
// Method-based tiering is therefore unsafe: gating GET/HEAD/OPTIONS on
|
|
46
|
+
// `plugins:read` with no CSRF let an editor (or a cross-origin page,
|
|
47
|
+
// since HEAD is CORS-safe) invoke a mutating admin route by choosing the
|
|
48
|
+
// method (#1853). Astro also dispatches HEAD to the GET export, so no
|
|
49
|
+
// explicit HEAD handler is needed to reach a "GET" route. Gate every
|
|
50
|
+
// private invocation on `plugins:manage` + CSRF regardless of method.
|
|
51
|
+
const denied = requirePerm(user, "plugins:manage");
|
|
47
52
|
if (denied) return denied;
|
|
48
53
|
|
|
49
54
|
// Token scope enforcement — plugin routes require "admin" scope.
|
|
@@ -51,16 +56,13 @@ const handleRequest: APIRoute = async ({ params, request, locals }) => {
|
|
|
51
56
|
const scopeError = requireScope(locals, "admin");
|
|
52
57
|
if (scopeError) return scopeError;
|
|
53
58
|
|
|
54
|
-
// CSRF protection
|
|
55
|
-
//
|
|
56
|
-
//
|
|
57
|
-
//
|
|
58
|
-
//
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
!locals.tokenScopes &&
|
|
62
|
-
request.headers.get("X-EmDash-Request") !== "1"
|
|
63
|
-
) {
|
|
59
|
+
// CSRF protection on private routes. Plugin routes use soft auth in the
|
|
60
|
+
// middleware (user resolved but not required), so the middleware's CSRF
|
|
61
|
+
// check doesn't run — enforce it here. Applied to every method because
|
|
62
|
+
// any method can trigger a state change (see above). Token-authed
|
|
63
|
+
// requests (which set tokenScopes) are exempt — tokens aren't ambient
|
|
64
|
+
// credentials like cookies.
|
|
65
|
+
if (!locals.tokenScopes && request.headers.get("X-EmDash-Request") !== "1") {
|
|
64
66
|
return apiError("CSRF_REJECTED", "Missing required header", 403);
|
|
65
67
|
}
|
|
66
68
|
}
|