emdash 0.35.0 → 0.36.0
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/activation-K0kGBWuJ.mjs +382 -0
- package/dist/activation-K0kGBWuJ.mjs.map +1 -0
- package/dist/{adapters-Bb1vG41D.d.mts → adapters-CzL3H752.d.mts} +3 -3
- package/dist/{adapters-Bb1vG41D.d.mts.map → adapters-CzL3H752.d.mts.map} +1 -1
- package/dist/{allowed-origins-DW7sYyqg.mjs → allowed-origins-maylGaHv.mjs} +2 -2
- package/dist/{allowed-origins-DW7sYyqg.mjs.map → allowed-origins-maylGaHv.mjs.map} +1 -1
- package/dist/api/route-utils.d.mts +3 -3
- package/dist/api/route-utils.mjs +22 -20
- package/dist/api/route-utils.mjs.map +1 -1
- package/dist/api/schemas/index.d.mts +2 -2
- package/dist/api/schemas/index.mjs +5 -5
- package/dist/api-B0w3uBiG.mjs +2269 -0
- package/dist/api-B0w3uBiG.mjs.map +1 -0
- package/dist/{api-tokens-KO24G1Fd.mjs → api-tokens-9YrrCoE6.mjs} +2 -2
- package/dist/{api-tokens-KO24G1Fd.mjs.map → api-tokens-9YrrCoE6.mjs.map} +1 -1
- package/dist/{apply-kUDt80-G.mjs → apply-B_VMpJ2P.mjs} +34 -35
- package/dist/{apply-kUDt80-G.mjs.map → apply-B_VMpJ2P.mjs.map} +1 -1
- package/dist/astro/index.d.mts +12 -12
- package/dist/astro/index.mjs +26 -15
- package/dist/astro/index.mjs.map +1 -1
- package/dist/astro/middleware/auth.d.mts +10 -10
- package/dist/astro/middleware/auth.d.mts.map +1 -1
- package/dist/astro/middleware/auth.mjs +10 -7
- package/dist/astro/middleware/auth.mjs.map +1 -1
- package/dist/astro/middleware/media-usage-write-fence.mjs +2 -2
- package/dist/astro/middleware/redirect.mjs +4 -4
- package/dist/astro/middleware/request-context.mjs +3 -3
- package/dist/astro/middleware/setup.mjs +1 -1
- package/dist/astro/middleware.d.mts +11 -12
- package/dist/astro/middleware.d.mts.map +1 -1
- package/dist/astro/middleware.mjs +168 -1305
- package/dist/astro/middleware.mjs.map +1 -1
- package/dist/astro/routes/api/admin/allowed-domains/_domain_.mjs +6 -6
- package/dist/astro/routes/api/admin/allowed-domains/index.mjs +6 -6
- package/dist/astro/routes/api/admin/api-tokens/_id_.mjs +3 -3
- package/dist/astro/routes/api/admin/api-tokens/index.mjs +4 -4
- package/dist/astro/routes/api/admin/byline-fields/_slug_/usage.mjs +4 -4
- package/dist/astro/routes/api/admin/byline-fields/_slug_.mjs +9 -9
- package/dist/astro/routes/api/admin/byline-fields/index.mjs +9 -9
- package/dist/astro/routes/api/admin/byline-fields/reorder.mjs +9 -9
- package/dist/astro/routes/api/admin/bylines/_id_/index.mjs +15 -15
- package/dist/astro/routes/api/admin/bylines/_id_/translations.mjs +15 -15
- package/dist/astro/routes/api/admin/bylines/index.mjs +15 -15
- package/dist/astro/routes/api/admin/comments/_id_/status.mjs +12 -12
- package/dist/astro/routes/api/admin/comments/_id_.mjs +4 -4
- package/dist/astro/routes/api/admin/comments/bulk.mjs +9 -9
- package/dist/astro/routes/api/admin/comments/counts.mjs +4 -4
- package/dist/astro/routes/api/admin/comments/index.mjs +9 -9
- package/dist/astro/routes/api/admin/hooks/exclusive/_hookName_.mjs +4 -4
- package/dist/astro/routes/api/admin/hooks/exclusive/index.mjs +3 -3
- package/dist/astro/routes/api/admin/media-usage/activation.d.mts +9 -0
- package/dist/astro/routes/api/admin/media-usage/activation.d.mts.map +1 -0
- package/dist/astro/routes/api/admin/media-usage/activation.mjs +46 -0
- package/dist/astro/routes/api/admin/media-usage/activation.mjs.map +1 -0
- package/dist/astro/routes/api/admin/media-usage/collection-deletions/index.mjs +14 -13
- package/dist/astro/routes/api/admin/media-usage/collection-deletions/index.mjs.map +1 -1
- package/dist/astro/routes/api/admin/media-usage/collection-deletions/retry.mjs +14 -13
- package/dist/astro/routes/api/admin/media-usage/collection-deletions/retry.mjs.map +1 -1
- package/dist/astro/routes/api/admin/media-usage/progress.d.mts +9 -0
- package/dist/astro/routes/api/admin/media-usage/progress.d.mts.map +1 -0
- package/dist/astro/routes/api/admin/media-usage/progress.mjs +44 -0
- package/dist/astro/routes/api/admin/media-usage/progress.mjs.map +1 -0
- package/dist/astro/routes/api/admin/media-usage/repair.mjs +16 -11
- package/dist/astro/routes/api/admin/media-usage/repair.mjs.map +1 -1
- package/dist/astro/routes/api/admin/media-usage/work/index.mjs +14 -13
- package/dist/astro/routes/api/admin/media-usage/work/index.mjs.map +1 -1
- package/dist/astro/routes/api/admin/media-usage/work/retry.mjs +14 -13
- package/dist/astro/routes/api/admin/media-usage/work/retry.mjs.map +1 -1
- package/dist/astro/routes/api/admin/oauth-clients/_id_.mjs +3 -3
- package/dist/astro/routes/api/admin/oauth-clients/index.mjs +3 -3
- package/dist/astro/routes/api/admin/plugins/_id_/disable.mjs +54 -48
- package/dist/astro/routes/api/admin/plugins/_id_/disable.mjs.map +1 -1
- package/dist/astro/routes/api/admin/plugins/_id_/enable.mjs +54 -48
- package/dist/astro/routes/api/admin/plugins/_id_/enable.mjs.map +1 -1
- package/dist/astro/routes/api/admin/plugins/_id_/index.mjs +52 -46
- package/dist/astro/routes/api/admin/plugins/_id_/index.mjs.map +1 -1
- package/dist/astro/routes/api/admin/plugins/_id_/mcp.mjs +4 -4
- package/dist/astro/routes/api/admin/plugins/_id_/settings.mjs +52 -46
- package/dist/astro/routes/api/admin/plugins/_id_/settings.mjs.map +1 -1
- package/dist/astro/routes/api/admin/plugins/_id_/uninstall.mjs +53 -47
- package/dist/astro/routes/api/admin/plugins/_id_/uninstall.mjs.map +1 -1
- package/dist/astro/routes/api/admin/plugins/_id_/update.mjs +53 -47
- package/dist/astro/routes/api/admin/plugins/_id_/update.mjs.map +1 -1
- package/dist/astro/routes/api/admin/plugins/index.mjs +52 -46
- package/dist/astro/routes/api/admin/plugins/index.mjs.map +1 -1
- package/dist/astro/routes/api/admin/plugins/marketplace/_id_/icon.mjs +2 -2
- package/dist/astro/routes/api/admin/plugins/marketplace/_id_/index.mjs +52 -46
- package/dist/astro/routes/api/admin/plugins/marketplace/_id_/index.mjs.map +1 -1
- package/dist/astro/routes/api/admin/plugins/marketplace/_id_/install.mjs +53 -47
- package/dist/astro/routes/api/admin/plugins/marketplace/_id_/install.mjs.map +1 -1
- package/dist/astro/routes/api/admin/plugins/marketplace/index.mjs +52 -46
- package/dist/astro/routes/api/admin/plugins/marketplace/index.mjs.map +1 -1
- package/dist/astro/routes/api/admin/plugins/registry/_id_/uninstall.mjs +53 -47
- package/dist/astro/routes/api/admin/plugins/registry/_id_/uninstall.mjs.map +1 -1
- package/dist/astro/routes/api/admin/plugins/registry/_id_/update.mjs +54 -48
- package/dist/astro/routes/api/admin/plugins/registry/_id_/update.mjs.map +1 -1
- package/dist/astro/routes/api/admin/plugins/registry/artifact.d.mts.map +1 -1
- package/dist/astro/routes/api/admin/plugins/registry/artifact.mjs +172 -133
- package/dist/astro/routes/api/admin/plugins/registry/artifact.mjs.map +1 -1
- package/dist/astro/routes/api/admin/plugins/registry/install.mjs +54 -48
- package/dist/astro/routes/api/admin/plugins/registry/install.mjs.map +1 -1
- package/dist/astro/routes/api/admin/plugins/updates.mjs +52 -46
- package/dist/astro/routes/api/admin/plugins/updates.mjs.map +1 -1
- package/dist/astro/routes/api/admin/themes/marketplace/_id_/index.mjs +52 -46
- package/dist/astro/routes/api/admin/themes/marketplace/_id_/index.mjs.map +1 -1
- package/dist/astro/routes/api/admin/themes/marketplace/_id_/thumbnail.mjs +2 -2
- package/dist/astro/routes/api/admin/themes/marketplace/index.mjs +52 -46
- package/dist/astro/routes/api/admin/themes/marketplace/index.mjs.map +1 -1
- package/dist/astro/routes/api/admin/users/_id_/disable.mjs +2 -2
- package/dist/astro/routes/api/admin/users/_id_/enable.mjs +1 -1
- package/dist/astro/routes/api/admin/users/_id_/index.mjs +7 -7
- package/dist/astro/routes/api/admin/users/_id_/send-recovery.mjs +3 -3
- package/dist/astro/routes/api/admin/users/index.mjs +6 -6
- package/dist/astro/routes/api/auth/dev-bypass.mjs +3 -3
- package/dist/astro/routes/api/auth/invite/accept.mjs +1 -1
- package/dist/astro/routes/api/auth/invite/complete.mjs +11 -11
- package/dist/astro/routes/api/auth/invite/index.mjs +8 -8
- package/dist/astro/routes/api/auth/invite/register-options.mjs +10 -10
- package/dist/astro/routes/api/auth/logout.mjs +2 -2
- package/dist/astro/routes/api/auth/magic-link/send.mjs +10 -10
- package/dist/astro/routes/api/auth/magic-link/verify.mjs +2 -2
- package/dist/astro/routes/api/auth/me.d.mts.map +1 -1
- package/dist/astro/routes/api/auth/me.mjs +19 -9
- package/dist/astro/routes/api/auth/me.mjs.map +1 -1
- package/dist/astro/routes/api/auth/mode.mjs +2 -2
- package/dist/astro/routes/api/auth/oauth/_provider_/callback.mjs +4 -4
- package/dist/astro/routes/api/auth/oauth/_provider_.mjs +2 -2
- package/dist/astro/routes/api/auth/passkey/_id_.mjs +6 -6
- package/dist/astro/routes/api/auth/passkey/index.mjs +1 -1
- package/dist/astro/routes/api/auth/passkey/options.mjs +12 -12
- package/dist/astro/routes/api/auth/passkey/register/options.mjs +10 -10
- package/dist/astro/routes/api/auth/passkey/register/verify.mjs +11 -11
- package/dist/astro/routes/api/auth/passkey/verify.mjs +11 -11
- package/dist/astro/routes/api/auth/signup/complete.mjs +11 -11
- package/dist/astro/routes/api/auth/signup/request.mjs +10 -10
- package/dist/astro/routes/api/auth/signup/verify.mjs +1 -1
- package/dist/astro/routes/api/comments/_collection_/_contentId_/index.mjs +13 -13
- package/dist/astro/routes/api/comments/_collection_/_contentId_/reactions.mjs +12 -12
- package/dist/astro/routes/api/content/_collection_/_id_/compare.mjs +2 -2
- package/dist/astro/routes/api/content/_collection_/_id_/discard-draft.mjs +3 -3
- package/dist/astro/routes/api/content/_collection_/_id_/duplicate.mjs +3 -3
- package/dist/astro/routes/api/content/_collection_/_id_/permanent.mjs +2 -2
- package/dist/astro/routes/api/content/_collection_/_id_/preview-url.mjs +11 -11
- package/dist/astro/routes/api/content/_collection_/_id_/publish.mjs +8 -8
- package/dist/astro/routes/api/content/_collection_/_id_/references/_relation_/children.mjs +16 -14
- package/dist/astro/routes/api/content/_collection_/_id_/references/_relation_/children.mjs.map +1 -1
- package/dist/astro/routes/api/content/_collection_/_id_/references/_relation_/parents.mjs +16 -14
- package/dist/astro/routes/api/content/_collection_/_id_/references/_relation_/parents.mjs.map +1 -1
- package/dist/astro/routes/api/content/_collection_/_id_/restore.mjs +3 -3
- package/dist/astro/routes/api/content/_collection_/_id_/revisions.mjs +2 -2
- package/dist/astro/routes/api/content/_collection_/_id_/schedule.mjs +8 -8
- package/dist/astro/routes/api/content/_collection_/_id_/terms/_taxonomy_.mjs +13 -13
- package/dist/astro/routes/api/content/_collection_/_id_/translations.mjs +2 -2
- package/dist/astro/routes/api/content/_collection_/_id_/unpublish.mjs +3 -3
- package/dist/astro/routes/api/content/_collection_/_id_.mjs +8 -8
- package/dist/astro/routes/api/content/_collection_/authors.mjs +2 -2
- package/dist/astro/routes/api/content/_collection_/index.mjs +8 -8
- package/dist/astro/routes/api/content/_collection_/trash.mjs +7 -7
- package/dist/astro/routes/api/dashboard.mjs +7 -7
- package/dist/astro/routes/api/dev/emails.mjs +2 -2
- package/dist/astro/routes/api/import/probe.d.mts +3 -3
- package/dist/astro/routes/api/import/probe.mjs +16 -16
- package/dist/astro/routes/api/import/wordpress/analyze.mjs +2 -2
- package/dist/astro/routes/api/import/wordpress/execute.d.mts +11 -11
- package/dist/astro/routes/api/import/wordpress/execute.mjs +12 -12
- package/dist/astro/routes/api/import/wordpress/media.d.mts +10 -10
- package/dist/astro/routes/api/import/wordpress/media.mjs +11 -11
- package/dist/astro/routes/api/import/wordpress/prepare.mjs +9 -9
- package/dist/astro/routes/api/import/wordpress/rewrite-urls.d.mts +11 -11
- package/dist/astro/routes/api/import/wordpress/rewrite-urls.mjs +12 -10
- package/dist/astro/routes/api/import/wordpress/rewrite-urls.mjs.map +1 -1
- package/dist/astro/routes/api/import/wordpress-plugin/analyze.d.mts +1 -1
- package/dist/astro/routes/api/import/wordpress-plugin/analyze.mjs +16 -16
- package/dist/astro/routes/api/import/wordpress-plugin/execute.d.mts +11 -11
- package/dist/astro/routes/api/import/wordpress-plugin/execute.mjs +26 -26
- package/dist/astro/routes/api/manifest.mjs +4 -4
- package/dist/astro/routes/api/mcp.mjs +42 -42
- package/dist/astro/routes/api/media/_id_/confirm.mjs +11 -11
- package/dist/astro/routes/api/media/_id_/upload.mjs +6 -6
- package/dist/astro/routes/api/media/_id_/usage.mjs +18 -13
- package/dist/astro/routes/api/media/_id_/usage.mjs.map +1 -1
- package/dist/astro/routes/api/media/_id_.d.mts.map +1 -1
- package/dist/astro/routes/api/media/_id_.mjs +21 -13
- package/dist/astro/routes/api/media/_id_.mjs.map +1 -1
- package/dist/astro/routes/api/media/file/_...key_.mjs +1 -1
- package/dist/astro/routes/api/media/folders/_id_.d.mts +10 -0
- package/dist/astro/routes/api/media/folders/_id_.d.mts.map +1 -0
- package/dist/astro/routes/api/media/folders/_id_.mjs +52 -0
- package/dist/astro/routes/api/media/folders/_id_.mjs.map +1 -0
- package/dist/astro/routes/api/media/folders/index.d.mts +9 -0
- package/dist/astro/routes/api/media/folders/index.d.mts.map +1 -0
- package/dist/astro/routes/api/media/folders/index.mjs +41 -0
- package/dist/astro/routes/api/media/folders/index.mjs.map +1 -0
- package/dist/astro/routes/api/media/providers/_providerId_/_itemId_.mjs +2 -2
- package/dist/astro/routes/api/media/providers/_providerId_/index.mjs +2 -2
- package/dist/astro/routes/api/media/providers/index.mjs +2 -2
- package/dist/astro/routes/api/media/upload-url.mjs +9 -9
- package/dist/astro/routes/api/media.d.mts.map +1 -1
- package/dist/astro/routes/api/media.mjs +28 -19
- package/dist/astro/routes/api/media.mjs.map +1 -1
- package/dist/astro/routes/api/menus/_name_/items/_id_.mjs +8 -8
- package/dist/astro/routes/api/menus/_name_/items.mjs +8 -8
- package/dist/astro/routes/api/menus/_name_/reorder.mjs +8 -8
- package/dist/astro/routes/api/menus/_name_/translations.mjs +8 -8
- package/dist/astro/routes/api/menus/_name_.mjs +8 -8
- package/dist/astro/routes/api/menus/index.mjs +8 -8
- package/dist/astro/routes/api/oauth/authorize.mjs +6 -6
- package/dist/astro/routes/api/oauth/device/authorize.mjs +5 -5
- package/dist/astro/routes/api/oauth/device/code.mjs +8 -8
- package/dist/astro/routes/api/oauth/device/token.mjs +7 -7
- package/dist/astro/routes/api/oauth/register.mjs +2 -2
- package/dist/astro/routes/api/oauth/token/refresh.mjs +5 -5
- package/dist/astro/routes/api/oauth/token/revoke.mjs +5 -5
- package/dist/astro/routes/api/oauth/token.mjs +5 -5
- package/dist/astro/routes/api/openapi.json.mjs +153 -6
- package/dist/astro/routes/api/openapi.json.mjs.map +1 -1
- package/dist/astro/routes/api/plugins/_pluginId_/_...path_.mjs +4 -4
- package/dist/astro/routes/api/redirects/404s/index.mjs +10 -10
- package/dist/astro/routes/api/redirects/404s/summary.mjs +10 -10
- package/dist/astro/routes/api/redirects/_id_.mjs +11 -11
- package/dist/astro/routes/api/redirects/index.mjs +11 -11
- package/dist/astro/routes/api/relations/_id_/index.mjs +16 -14
- package/dist/astro/routes/api/relations/_id_/index.mjs.map +1 -1
- package/dist/astro/routes/api/relations/_id_/translations.mjs +11 -9
- package/dist/astro/routes/api/relations/_id_/translations.mjs.map +1 -1
- package/dist/astro/routes/api/relations/index.mjs +16 -14
- package/dist/astro/routes/api/relations/index.mjs.map +1 -1
- package/dist/astro/routes/api/revisions/_revisionId_/index.mjs +2 -2
- package/dist/astro/routes/api/revisions/_revisionId_/restore.mjs +3 -3
- package/dist/astro/routes/api/schema/collections/_slug_/fields/_fieldSlug_.mjs +52 -46
- package/dist/astro/routes/api/schema/collections/_slug_/fields/_fieldSlug_.mjs.map +1 -1
- package/dist/astro/routes/api/schema/collections/_slug_/fields/index.mjs +52 -46
- package/dist/astro/routes/api/schema/collections/_slug_/fields/index.mjs.map +1 -1
- package/dist/astro/routes/api/schema/collections/_slug_/fields/reorder.mjs +52 -46
- package/dist/astro/routes/api/schema/collections/_slug_/fields/reorder.mjs.map +1 -1
- package/dist/astro/routes/api/schema/collections/_slug_/index.mjs +52 -46
- package/dist/astro/routes/api/schema/collections/_slug_/index.mjs.map +1 -1
- package/dist/astro/routes/api/schema/collections/index.mjs +52 -46
- package/dist/astro/routes/api/schema/collections/index.mjs.map +1 -1
- package/dist/astro/routes/api/schema/collections/reorder.mjs +52 -46
- package/dist/astro/routes/api/schema/collections/reorder.mjs.map +1 -1
- package/dist/astro/routes/api/schema/index.mjs +10 -8
- package/dist/astro/routes/api/schema/index.mjs.map +1 -1
- package/dist/astro/routes/api/schema/orphans/_slug_.mjs +52 -46
- package/dist/astro/routes/api/schema/orphans/_slug_.mjs.map +1 -1
- package/dist/astro/routes/api/schema/orphans/index.mjs +52 -46
- package/dist/astro/routes/api/schema/orphans/index.mjs.map +1 -1
- package/dist/astro/routes/api/search/enable.mjs +10 -10
- package/dist/astro/routes/api/search/index.mjs +9 -9
- package/dist/astro/routes/api/search/rebuild.mjs +10 -10
- package/dist/astro/routes/api/search/stats.mjs +5 -5
- package/dist/astro/routes/api/search/suggest.mjs +9 -9
- package/dist/astro/routes/api/sections/_slug_.mjs +9 -9
- package/dist/astro/routes/api/sections/index.mjs +9 -9
- package/dist/astro/routes/api/settings/backups/archives/_name_.mjs +6 -6
- package/dist/astro/routes/api/settings/backups/archives/index.mjs +5 -5
- package/dist/astro/routes/api/settings/backups/export.mjs +6 -6
- package/dist/astro/routes/api/settings/backups/index.mjs +7 -7
- package/dist/astro/routes/api/settings/email.mjs +4 -4
- package/dist/astro/routes/api/settings.mjs +13 -13
- package/dist/astro/routes/api/setup/admin-verify.mjs +12 -12
- package/dist/astro/routes/api/setup/admin.mjs +11 -11
- package/dist/astro/routes/api/setup/dev-bypass.d.mts.map +1 -1
- package/dist/astro/routes/api/setup/dev-bypass.mjs +34 -27
- package/dist/astro/routes/api/setup/dev-bypass.mjs.map +1 -1
- package/dist/astro/routes/api/setup/dev-reset.mjs +2 -2
- package/dist/astro/routes/api/setup/index.mjs +31 -29
- package/dist/astro/routes/api/setup/index.mjs.map +1 -1
- package/dist/astro/routes/api/setup/status.mjs +3 -3
- package/dist/astro/routes/api/snapshot.mjs +7 -7
- package/dist/astro/routes/api/taxonomies/_name_/reorder.mjs +13 -13
- package/dist/astro/routes/api/taxonomies/_name_/terms/_slug_/translations.mjs +13 -13
- package/dist/astro/routes/api/taxonomies/_name_/terms/_slug_.mjs +13 -13
- package/dist/astro/routes/api/taxonomies/_name_/terms/index.mjs +13 -13
- package/dist/astro/routes/api/taxonomies/_name_/translations.mjs +13 -13
- package/dist/astro/routes/api/taxonomies/_name_.mjs +13 -13
- package/dist/astro/routes/api/taxonomies/index.mjs +13 -13
- package/dist/astro/routes/api/themes/preview.mjs +5 -5
- package/dist/astro/routes/api/typegen.mjs +4 -4
- package/dist/astro/routes/api/well-known/auth.mjs +2 -2
- package/dist/astro/routes/api/well-known/oauth-authorization-server.mjs +2 -2
- package/dist/astro/routes/api/well-known/oauth-protected-resource.mjs +2 -2
- package/dist/astro/routes/api/widget-areas/_name_/reorder.mjs +7 -7
- package/dist/astro/routes/api/widget-areas/_name_/widgets/_id_.mjs +10 -10
- package/dist/astro/routes/api/widget-areas/_name_/widgets.mjs +10 -10
- package/dist/astro/routes/api/widget-areas/_name_.mjs +5 -5
- package/dist/astro/routes/api/widget-areas/index.mjs +10 -10
- package/dist/astro/routes/api/widget-components.mjs +2 -2
- package/dist/astro/routes/robots.txt.mjs +6 -6
- package/dist/astro/routes/sitemap-_collection_.xml.mjs +9 -9
- package/dist/astro/routes/sitemap.xml.mjs +7 -7
- package/dist/astro/types.d.mts +19 -14
- package/dist/astro/types.d.mts.map +1 -1
- package/dist/auth/providers/github.d.mts +1 -1
- package/dist/auth/providers/google.d.mts +1 -1
- package/dist/{authorize-DUElxgOQ.mjs → authorize-ByYs-Uxs.mjs} +2 -2
- package/dist/{authorize-DUElxgOQ.mjs.map → authorize-ByYs-Uxs.mjs.map} +1 -1
- package/dist/{backup-DWYpJlLj.mjs → backup-ChyHfIoX.mjs} +5 -5
- package/dist/{backup-DWYpJlLj.mjs.map → backup-ChyHfIoX.mjs.map} +1 -1
- package/dist/{bundle-vn56sLos.mjs → bundle-DZFhFurR.mjs} +4 -4
- package/dist/{bundle-vn56sLos.mjs.map → bundle-DZFhFurR.mjs.map} +1 -1
- package/dist/{byline-yjvWq4ip.mjs → byline-Cpnwrje1.mjs} +6 -6
- package/dist/{byline-yjvWq4ip.mjs.map → byline-Cpnwrje1.mjs.map} +1 -1
- package/dist/{byline-fields-txaLGoME.mjs → byline-fields-CAyA_Umd.mjs} +2 -2
- package/dist/{byline-fields-txaLGoME.mjs.map → byline-fields-CAyA_Umd.mjs.map} +1 -1
- package/dist/{byline-registry-DDun8sxh.mjs → byline-registry-Bpu9-MVs.mjs} +2 -2
- package/dist/{byline-registry-DDun8sxh.mjs.map → byline-registry-Bpu9-MVs.mjs.map} +1 -1
- package/dist/{bylines-DjXS5p0P.mjs → bylines-BSo9B9RX.mjs} +7 -7
- package/dist/{bylines-DjXS5p0P.mjs.map → bylines-BSo9B9RX.mjs.map} +1 -1
- package/dist/{bylines-Bu7pchQ4.mjs → bylines-CHjvehVX.mjs} +3 -3
- package/dist/{bylines-Bu7pchQ4.mjs.map → bylines-CHjvehVX.mjs.map} +1 -1
- package/dist/{cache-C46-3Irl.mjs → cache-5VirJ2Cn.mjs} +4 -4
- package/dist/{cache-C46-3Irl.mjs.map → cache-5VirJ2Cn.mjs.map} +1 -1
- package/dist/capture-triggers-CNW1q3HK.mjs +362 -0
- package/dist/capture-triggers-CNW1q3HK.mjs.map +1 -0
- package/dist/{challenge-store-SIL5DsF2.mjs → challenge-store-D5pSY2S1.mjs} +1 -1
- package/dist/{challenge-store-SIL5DsF2.mjs.map → challenge-store-D5pSY2S1.mjs.map} +1 -1
- package/dist/{chunks-fiZ8G9RJ.mjs → chunks-bNiX6_DR.mjs} +2 -2
- package/dist/{chunks-fiZ8G9RJ.mjs.map → chunks-bNiX6_DR.mjs.map} +1 -1
- package/dist/cli/index.mjs +36 -52
- package/dist/cli/index.mjs.map +1 -1
- package/dist/client/cf-access.d.mts +1 -1
- package/dist/client/index.d.mts +74 -4
- package/dist/client/index.d.mts.map +1 -1
- package/dist/client/index.mjs +54 -2
- package/dist/client/index.mjs.map +1 -1
- package/dist/{collection-deletion-DQPvMD8R.mjs → collection-deletion-m_oi2c0N.mjs} +13 -356
- package/dist/collection-deletion-m_oi2c0N.mjs.map +1 -0
- package/dist/{comment-Dxlep6cE.mjs → comment-DhvLEdhQ.mjs} +1 -1
- package/dist/{comment-Dxlep6cE.mjs.map → comment-DhvLEdhQ.mjs.map} +1 -1
- package/dist/{comment-reaction-D-2J84UE.mjs → comment-reaction-CRuItEjt.mjs} +2 -2
- package/dist/{comment-reaction-D-2J84UE.mjs.map → comment-reaction-CRuItEjt.mjs.map} +1 -1
- package/dist/{comments-CTfZtLmM.mjs → comments-CLj4bi8I.mjs} +2 -2
- package/dist/{comments-CTfZtLmM.mjs.map → comments-CLj4bi8I.mjs.map} +1 -1
- package/dist/{components-CQy3lh9x.mjs → components-v4U4DT2y.mjs} +1 -1
- package/dist/{components-CQy3lh9x.mjs.map → components-v4U4DT2y.mjs.map} +1 -1
- package/dist/{config-COQzTe5Q.d.mts → config-DrfghTPe.d.mts} +1 -1
- package/dist/{config-COQzTe5Q.d.mts.map → config-DrfghTPe.d.mts.map} +1 -1
- package/dist/{content-ZHCc1ngN.mjs → content-CP-SeXNa.mjs} +5 -4
- package/dist/content-CP-SeXNa.mjs.map +1 -0
- package/dist/{content-list-query-wJ2WN8Vp.d.mts → content-list-query-BhejKVqb.d.mts} +1 -1
- package/dist/{content-list-query-wJ2WN8Vp.d.mts.map → content-list-query-BhejKVqb.d.mts.map} +1 -1
- package/dist/{content-refresh-B_8SJzuU.mjs → content-refresh-DLOfIhYc.mjs} +1094 -93
- package/dist/content-refresh-DLOfIhYc.mjs.map +1 -0
- package/dist/{media-usage-BZCydfvu.mjs → content-repair-BCxzy0r4.mjs} +5 -196
- package/dist/content-repair-BCxzy0r4.mjs.map +1 -0
- package/dist/{context-ZldbZcle.mjs → context-BR5hRWiK.mjs} +13 -13
- package/dist/{context-ZldbZcle.mjs.map → context-BR5hRWiK.mjs.map} +1 -1
- package/dist/{cron-Y9aLtgrA.mjs → cron-CWfWrWKG.mjs} +1 -1
- package/dist/{cron-Y9aLtgrA.mjs.map → cron-CWfWrWKG.mjs.map} +1 -1
- package/dist/{dashboard-DvHbk_cv.mjs → dashboard-CkIV2rnQ.mjs} +5 -5
- package/dist/{dashboard-DvHbk_cv.mjs.map → dashboard-CkIV2rnQ.mjs.map} +1 -1
- package/dist/db/index.d.mts +3 -3
- package/dist/db/index.mjs +3 -3
- package/dist/db/index.mjs.map +1 -1
- package/dist/db/libsql-migrations.d.mts +1 -1
- package/dist/db/libsql-migrations.mjs +4 -4
- package/dist/db/libsql.d.mts +1 -1
- package/dist/db/postgres-migrations.d.mts +1 -1
- package/dist/db/postgres-migrations.mjs +4 -4
- package/dist/db/postgres.d.mts +1 -1
- package/dist/db/sqlite-migrations.d.mts +1 -1
- package/dist/db/sqlite-migrations.mjs +4 -4
- package/dist/db/sqlite.d.mts +1 -1
- package/dist/db/sqlite.mjs +3 -3
- package/dist/db/sqlite.mjs.map +1 -1
- package/dist/{default-DdDl3fxv.mjs → default-YMEfcQUx.mjs} +1 -1
- package/dist/{default-DdDl3fxv.mjs.map → default-YMEfcQUx.mjs.map} +1 -1
- package/dist/{deferred-tasks-SDWxrgzJ.d.mts → deferred-tasks-DfqxH5Xf.d.mts} +1 -1
- package/dist/{deferred-tasks-SDWxrgzJ.d.mts.map → deferred-tasks-DfqxH5Xf.d.mts.map} +1 -1
- package/dist/{device-flow-C0GdD_z8.mjs → device-flow-CojjSBwb.mjs} +5 -5
- package/dist/{device-flow-C0GdD_z8.mjs.map → device-flow-CojjSBwb.mjs.map} +1 -1
- package/dist/{direct-executor-CDXeJCSs.mjs → direct-executor-BWeWiRYB.mjs} +3 -3
- package/dist/{direct-executor-CDXeJCSs.mjs.map → direct-executor-BWeWiRYB.mjs.map} +1 -1
- package/dist/{dist-D_6CKR8z.mjs → dist-89xCrGqi.mjs} +1 -1
- package/dist/{dist-D_6CKR8z.mjs.map → dist-89xCrGqi.mjs.map} +1 -1
- package/dist/{email-console-BHNjIwiB.mjs → email-console-CEJgR_LB.mjs} +1 -1
- package/dist/{email-console-BHNjIwiB.mjs.map → email-console-CEJgR_LB.mjs.map} +1 -1
- package/dist/{enrich-_ySMEvEE.mjs → enrich-BX0IDp4z.mjs} +3 -3
- package/dist/{enrich-_ySMEvEE.mjs.map → enrich-BX0IDp4z.mjs.map} +1 -1
- package/dist/{error-DupyJZE2.mjs → error-D9w94fjV.mjs} +2 -2
- package/dist/{error-DupyJZE2.mjs.map → error-D9w94fjV.mjs.map} +1 -1
- package/dist/{errors-CLUPm7aD.mjs → errors-n2j49uNf.mjs} +22 -2
- package/dist/errors-n2j49uNf.mjs.map +1 -0
- package/dist/{escape-DUY2r2Zs.mjs → escape-DN4Qmjsl.mjs} +1 -1
- package/dist/{escape-DUY2r2Zs.mjs.map → escape-DN4Qmjsl.mjs.map} +1 -1
- package/dist/{field-defs-cache-BzwBlJrR.mjs → field-defs-cache-Bh4q6oar.mjs} +5 -5
- package/dist/{field-defs-cache-BzwBlJrR.mjs.map → field-defs-cache-Bh4q6oar.mjs.map} +1 -1
- package/dist/focal-point-BeWFo6Xx.mjs +23 -0
- package/dist/focal-point-BeWFo6Xx.mjs.map +1 -0
- package/dist/{fts-manager-DyZEohZC.mjs → fts-manager-BhOdW0bi.mjs} +3 -3
- package/dist/{fts-manager-DyZEohZC.mjs.map → fts-manager-BhOdW0bi.mjs.map} +1 -1
- package/dist/{hash-Cg0TXJPV.mjs → hash-CTcngWvj.mjs} +1 -1
- package/dist/{hash-Cg0TXJPV.mjs.map → hash-CTcngWvj.mjs.map} +1 -1
- package/dist/{hreflang-DwT2E0Sa.d.mts → hreflang-7pTHsLZJ.d.mts} +2 -2
- package/dist/{hreflang-DwT2E0Sa.d.mts.map → hreflang-7pTHsLZJ.d.mts.map} +1 -1
- package/dist/{hreflang-BBe83kKa.mjs → hreflang-Huc6O5wa.mjs} +7 -7
- package/dist/{hreflang-BBe83kKa.mjs.map → hreflang-Huc6O5wa.mjs.map} +1 -1
- package/dist/{identity-Ys6Dlc9C.mjs → identity-DXmb4aVp.mjs} +3 -3
- package/dist/{identity-Ys6Dlc9C.mjs.map → identity-DXmb4aVp.mjs.map} +1 -1
- package/dist/{import-DPkLmeXO.mjs → import-C4_O3KXU.mjs} +5 -5
- package/dist/{import-DPkLmeXO.mjs.map → import-C4_O3KXU.mjs.map} +1 -1
- package/dist/{index-C9KuQyO-.d.mts → index-6bRee8zb.d.mts} +3 -3
- package/dist/{index-C9KuQyO-.d.mts.map → index-6bRee8zb.d.mts.map} +1 -1
- package/dist/{index-BVBZj4-7.d.mts → index-DWbJrsAg.d.mts} +128 -52
- package/dist/index-DWbJrsAg.d.mts.map +1 -0
- package/dist/index.d.mts +21 -21
- package/dist/index.mjs +78 -72
- package/dist/{init-lock-6b309ZrF.mjs → init-lock-DJkX6Hto.mjs} +1 -1
- package/dist/{init-lock-6b309ZrF.mjs.map → init-lock-DJkX6Hto.mjs.map} +1 -1
- package/dist/{load-YJ2xl3ra.mjs → load-Bo7fZAbg.mjs} +2 -2
- package/dist/{load-YJ2xl3ra.mjs.map → load-Bo7fZAbg.mjs.map} +1 -1
- package/dist/{loader-CdG_Ci3H.mjs → loader-ZsjE4paL.mjs} +2 -2
- package/dist/{loader-CdG_Ci3H.mjs.map → loader-ZsjE4paL.mjs.map} +1 -1
- package/dist/{manifest-builder-B252yQUf.mjs → manifest-builder-QXuqvVMP.mjs} +2 -2
- package/dist/{manifest-builder-B252yQUf.mjs.map → manifest-builder-QXuqvVMP.mjs.map} +1 -1
- package/dist/{manifest-schema-BXbUAHod.mjs → manifest-schema-CUYPfCEH.mjs} +1 -1
- package/dist/{manifest-schema-BXbUAHod.mjs.map → manifest-schema-CUYPfCEH.mjs.map} +1 -1
- package/dist/media/image-endpoint.mjs +1 -1
- package/dist/media/index.d.mts +1 -1
- package/dist/media/index.mjs +13 -3
- package/dist/media/index.mjs.map +1 -1
- package/dist/media/local-runtime.d.mts +14 -12
- package/dist/media/local-runtime.d.mts.map +1 -1
- package/dist/media/local-runtime.mjs +11 -5
- package/dist/media/local-runtime.mjs.map +1 -1
- package/dist/{media-BWWWb8kg.mjs → media-BjwNuLEu.mjs} +100 -6
- package/dist/media-BjwNuLEu.mjs.map +1 -0
- package/dist/{media-CzhAn2--.mjs → media-D6SeAfBl.mjs} +41 -12
- package/dist/media-D6SeAfBl.mjs.map +1 -0
- package/dist/{media-allowlist-D6x-Us02.mjs → media-allowlist-D35v7bmL.mjs} +3 -2
- package/dist/media-allowlist-D35v7bmL.mjs.map +1 -0
- package/dist/media-folders-D-0CmRZj.mjs +210 -0
- package/dist/media-folders-D-0CmRZj.mjs.map +1 -0
- package/dist/{media-upload-CHBVn6m-.mjs → media-upload-C7bLXGcI.mjs} +9 -9
- package/dist/{media-upload-CHBVn6m-.mjs.map → media-upload-C7bLXGcI.mjs.map} +1 -1
- package/dist/{media-url-BvoX88FA.mjs → media-url-DH7giMx_.mjs} +1 -1
- package/dist/{media-url-BvoX88FA.mjs.map → media-url-DH7giMx_.mjs.map} +1 -1
- package/dist/media-usage-BTRJvS6V.mjs +1833 -0
- package/dist/media-usage-BTRJvS6V.mjs.map +1 -0
- package/dist/media-usage-activation-Dx0kPV6b.mjs +78 -0
- package/dist/media-usage-activation-Dx0kPV6b.mjs.map +1 -0
- package/dist/{media-usage-work-DrCbqBcl.mjs → media-usage-work-C-fhM30c.mjs} +221 -59
- package/dist/media-usage-work-C-fhM30c.mjs.map +1 -0
- package/dist/{media-usage-work-CLo_6tct.mjs → media-usage-work-DWb2XPMI.mjs} +4 -4
- package/dist/{media-usage-work-CLo_6tct.mjs.map → media-usage-work-DWb2XPMI.mjs.map} +1 -1
- package/dist/{media-usage-write-fence-aHEgN1zB.mjs → media-usage-write-fence-BwoJVRDC.mjs} +2 -2
- package/dist/{media-usage-write-fence-aHEgN1zB.mjs.map → media-usage-write-fence-BwoJVRDC.mjs.map} +1 -1
- package/dist/{menus-TCNSd2vp.mjs → menus-CD7EFLwz.mjs} +3 -3
- package/dist/{menus-TCNSd2vp.mjs.map → menus-CD7EFLwz.mjs.map} +1 -1
- package/dist/{menus-DSo5QeW0.mjs → menus-CNg0QlDt.mjs} +42 -26
- package/dist/menus-CNg0QlDt.mjs.map +1 -0
- package/dist/migrations/index.d.mts +1 -1
- package/dist/migrations/index.mjs +3 -3
- package/dist/{mime-DfIVjNkr.mjs → mime-CUIG6x84.mjs} +1 -1
- package/dist/mime-CUIG6x84.mjs.map +1 -0
- package/dist/{mode-BDoH_WcF.mjs → mode-DaUM_MB2.mjs} +1 -1
- package/dist/{mode-BDoH_WcF.mjs.map → mode-DaUM_MB2.mjs.map} +1 -1
- package/dist/node-sqlite-compat-Udb4Y-rs.mjs +46 -0
- package/dist/node-sqlite-compat-Udb4Y-rs.mjs.map +1 -0
- package/dist/{normalize-Bc-s_r-a.mjs → normalize-CSxdKBVa.mjs} +22 -1
- package/dist/normalize-CSxdKBVa.mjs.map +1 -0
- package/dist/{oauth-authorization-iOikmrJd.mjs → oauth-authorization-Dpsb-fMJ.mjs} +5 -5
- package/dist/{oauth-authorization-iOikmrJd.mjs.map → oauth-authorization-Dpsb-fMJ.mjs.map} +1 -1
- package/dist/{oauth-clients-CvI0nHMJ.mjs → oauth-clients-Bxnoe_67.mjs} +1 -1
- package/dist/{oauth-clients-CvI0nHMJ.mjs.map → oauth-clients-Bxnoe_67.mjs.map} +1 -1
- package/dist/{oauth-state-store-Ba8KZlwW.mjs → oauth-state-store-0C4s0K6w.mjs} +1 -1
- package/dist/{oauth-state-store-Ba8KZlwW.mjs.map → oauth-state-store-0C4s0K6w.mjs.map} +1 -1
- package/dist/{oauth-user-lookup-C5SQwGYC.mjs → oauth-user-lookup-wlGYSeqX.mjs} +1 -1
- package/dist/{oauth-user-lookup-C5SQwGYC.mjs.map → oauth-user-lookup-wlGYSeqX.mjs.map} +1 -1
- package/dist/object-cache/memory.d.mts +1 -1
- package/dist/{options-CBXIHUoT.mjs → options-BHPeIbBd.mjs} +1 -1
- package/dist/{options-CBXIHUoT.mjs.map → options-BHPeIbBd.mjs.map} +1 -1
- package/dist/{options--hhz-jZ1.d.mts → options-BhZIeFY1.d.mts} +3 -3
- package/dist/{options--hhz-jZ1.d.mts.map → options-BhZIeFY1.d.mts.map} +1 -1
- package/dist/page/index.d.mts +2 -2
- package/dist/{parse-DFbuc-Fh.mjs → parse-BRJg1kz8.mjs} +2 -2
- package/dist/{parse-DFbuc-Fh.mjs.map → parse-BRJg1kz8.mjs.map} +1 -1
- package/dist/{passkey-config-DFAmUyuE.mjs → passkey-config-B3P0nHRR.mjs} +1 -1
- package/dist/{passkey-config-DFAmUyuE.mjs.map → passkey-config-B3P0nHRR.mjs.map} +1 -1
- package/dist/{patterns-CiyXeDgr.mjs → patterns-D9iDO3j8.mjs} +1 -1
- package/dist/{patterns-CiyXeDgr.mjs.map → patterns-D9iDO3j8.mjs.map} +1 -1
- package/dist/{placeholder-Dp0K3RkD.d.mts → placeholder-BR4ZhVJl.d.mts} +7 -1
- package/dist/placeholder-BR4ZhVJl.d.mts.map +1 -0
- package/dist/plugin-types.d.mts +1 -1
- package/dist/plugin-utils.d.mts +10 -10
- package/dist/plugins/adapt-sandbox-entry.d.mts +10 -10
- package/dist/plugins/adapt-sandbox-entry.mjs +2 -2
- package/dist/{policy-TluUIxuu.mjs → policy-BVRganJQ.mjs} +2 -2
- package/dist/{policy-TluUIxuu.mjs.map → policy-BVRganJQ.mjs.map} +1 -1
- package/dist/{portable-text-imBW5cHK.mjs → portable-text-C8Tvp4_g.mjs} +1 -1
- package/dist/{portable-text-imBW5cHK.mjs.map → portable-text-C8Tvp4_g.mjs.map} +1 -1
- package/dist/{preview-PW-nOnq4.mjs → preview-dn2dUyM0.mjs} +2 -2
- package/dist/{preview-PW-nOnq4.mjs.map → preview-dn2dUyM0.mjs.map} +1 -1
- package/dist/{protocol-DjsJHTlK.d.mts → protocol-CuBEsqgE.d.mts} +2 -2
- package/dist/{protocol-DjsJHTlK.d.mts.map → protocol-CuBEsqgE.d.mts.map} +1 -1
- package/dist/{public-url-CWoFhQT8.mjs → public-url-DRz_AinV.mjs} +1 -1
- package/dist/{public-url-CWoFhQT8.mjs.map → public-url-DRz_AinV.mjs.map} +1 -1
- package/dist/{query-zTVAR1Sl.mjs → query-D18vTdha.mjs} +14 -14
- package/dist/{query-zTVAR1Sl.mjs.map → query-D18vTdha.mjs.map} +1 -1
- package/dist/{query-BWs7O5Il.mjs → query-tZDEdtCN.mjs} +4 -4
- package/dist/{query-BWs7O5Il.mjs.map → query-tZDEdtCN.mjs.map} +1 -1
- package/dist/{rate-limit-Bx4g9m3p.mjs → rate-limit-on7KPo-v.mjs} +2 -2
- package/dist/{rate-limit-Bx4g9m3p.mjs.map → rate-limit-on7KPo-v.mjs.map} +1 -1
- package/dist/{redirect-COsS6SWJ.mjs → redirect-CZkbozu9.mjs} +2 -2
- package/dist/{redirect-COsS6SWJ.mjs.map → redirect-CZkbozu9.mjs.map} +1 -1
- package/dist/{redirect-BgAOGHDq.mjs → redirect-DrbEmU9a.mjs} +1 -1
- package/dist/{redirect-BgAOGHDq.mjs.map → redirect-DrbEmU9a.mjs.map} +1 -1
- package/dist/{redirects-DyChwDkG.mjs → redirects-BahWiu8Z.mjs} +5 -5
- package/dist/{redirects-DyChwDkG.mjs.map → redirects-BahWiu8Z.mjs.map} +1 -1
- package/dist/{redirects-DTDHWH31.mjs → redirects-CRIM55KH.mjs} +6 -6
- package/dist/{redirects-DTDHWH31.mjs.map → redirects-CRIM55KH.mjs.map} +1 -1
- package/dist/{api-BeBglVxU.mjs → registry-BiO5WwPq.mjs} +483 -2462
- package/dist/registry-BiO5WwPq.mjs.map +1 -0
- package/dist/{registry-Cqa2I749.mjs → registry-Cx-jEJOS.mjs} +9 -123
- package/dist/registry-Cx-jEJOS.mjs.map +1 -0
- package/dist/{relation-BnHB0T4J.mjs → relation-A6wLF_DS.mjs} +2 -2
- package/dist/{relation-BnHB0T4J.mjs.map → relation-A6wLF_DS.mjs.map} +1 -1
- package/dist/{relations-BBApI4e2.mjs → relations-BTPM2saV.mjs} +2 -2
- package/dist/{relations-BBApI4e2.mjs.map → relations-BTPM2saV.mjs.map} +1 -1
- package/dist/{relations-BHo5A8Zf.d.mts → relations-C7B46bcU.d.mts} +192 -33
- package/dist/relations-C7B46bcU.d.mts.map +1 -0
- package/dist/{relations-D5sM5fW0.mjs → relations-Cj5hZ6Zg.mjs} +4 -4
- package/dist/{relations-D5sM5fW0.mjs.map → relations-Cj5hZ6Zg.mjs.map} +1 -1
- package/dist/{request-cache-BSUptuJR.mjs → request-cache-DH9zdCOD.mjs} +1 -1
- package/dist/{request-cache-BSUptuJR.mjs.map → request-cache-DH9zdCOD.mjs.map} +1 -1
- package/dist/request-context.d.mts +1 -1
- package/dist/{request-meta-DgZJh3zG.mjs → request-meta-DRp5ENd_.mjs} +2 -2
- package/dist/{request-meta-DgZJh3zG.mjs.map → request-meta-DRp5ENd_.mjs.map} +1 -1
- package/dist/{resolve-DOhVEvty.mjs → resolve-DxUpTMmE.mjs} +1 -1
- package/dist/{resolve-DOhVEvty.mjs.map → resolve-DxUpTMmE.mjs.map} +1 -1
- package/dist/{runner-C1T11CfC.mjs → runner-77GOZCnH.mjs} +410 -286
- package/dist/runner-77GOZCnH.mjs.map +1 -0
- package/dist/{runner-BYHZn3Jy.d.mts → runner-zgqA_CqP.d.mts} +2 -2
- package/dist/{runner-BYHZn3Jy.d.mts.map → runner-zgqA_CqP.d.mts.map} +1 -1
- package/dist/runtime.d.mts +11 -11
- package/dist/runtime.mjs +1 -1
- package/dist/{schema-DZ5YVVZj.mjs → schema-BY-oVntF.mjs} +3 -3
- package/dist/{schema-DZ5YVVZj.mjs.map → schema-BY-oVntF.mjs.map} +1 -1
- package/dist/{schema-2AOsSn2v.mjs → schema-Cw9kVK0I.mjs} +35 -5
- package/dist/{schema-2AOsSn2v.mjs.map → schema-Cw9kVK0I.mjs.map} +1 -1
- package/dist/{scopes-8ClPF2bC.mjs → scopes-vMR1uIbt.mjs} +3 -3
- package/dist/{scopes-8ClPF2bC.mjs.map → scopes-vMR1uIbt.mjs.map} +1 -1
- package/dist/{search-u1QYdOCG.mjs → search-CfT3KxO5.mjs} +4 -4
- package/dist/{search-u1QYdOCG.mjs.map → search-CfT3KxO5.mjs.map} +1 -1
- package/dist/{secrets-BEgsAQEU.mjs → secrets-BH2Qow1-.mjs} +3 -3
- package/dist/{secrets-BEgsAQEU.mjs.map → secrets-BH2Qow1-.mjs.map} +1 -1
- package/dist/{sections-DmHviGyM.mjs → sections-DTfjyf1z.mjs} +2 -2
- package/dist/{sections-DmHviGyM.mjs.map → sections-DTfjyf1z.mjs.map} +1 -1
- package/dist/seed/index.d.mts +2 -2
- package/dist/seed/index.mjs +24 -22
- package/dist/seo/index.d.mts +3 -3
- package/dist/seo/index.mjs +16 -14
- package/dist/seo/index.mjs.map +1 -1
- package/dist/{seo-AFpVvTqr.mjs → seo-BSiTIXzd.mjs} +1 -1
- package/dist/{seo-AFpVvTqr.mjs.map → seo-BSiTIXzd.mjs.map} +1 -1
- package/dist/{seo-Dq4G-RrO.mjs → seo-Cm-dtvgk.mjs} +2 -2
- package/dist/{seo-Dq4G-RrO.mjs.map → seo-Cm-dtvgk.mjs.map} +1 -1
- package/dist/{service-BpArayPr.mjs → service-DYsDHEKe.mjs} +3 -3
- package/dist/{service-BpArayPr.mjs.map → service-DYsDHEKe.mjs.map} +1 -1
- package/dist/{session-user-BEorKVT-.mjs → session-user-CNAfvsdw.mjs} +1 -1
- package/dist/{session-user-BEorKVT-.mjs.map → session-user-CNAfvsdw.mjs.map} +1 -1
- package/dist/{settings-xRdoUZr0.mjs → settings-BgN-0DT-.mjs} +6 -6
- package/dist/{settings-xRdoUZr0.mjs.map → settings-BgN-0DT-.mjs.map} +1 -1
- package/dist/{settings-DE9xtzqd.mjs → settings-DjtkUo__.mjs} +3 -3
- package/dist/{settings-DE9xtzqd.mjs.map → settings-DjtkUo__.mjs.map} +1 -1
- package/dist/{setup-complete-BnT8pq_C.mjs → setup-complete-CcpXaPU7.mjs} +2 -2
- package/dist/{setup-complete-BnT8pq_C.mjs.map → setup-complete-CcpXaPU7.mjs.map} +1 -1
- package/dist/{setup-nonce-CBitf_oQ.mjs → setup-nonce-Reyw30jg.mjs} +1 -1
- package/dist/{setup-nonce-CBitf_oQ.mjs.map → setup-nonce-Reyw30jg.mjs.map} +1 -1
- package/dist/{single-flight-cache-B0eLKS6K.mjs → single-flight-cache-BPuGPdcN.mjs} +2 -2
- package/dist/{single-flight-cache-B0eLKS6K.mjs.map → single-flight-cache-BPuGPdcN.mjs.map} +1 -1
- package/dist/{site-url-DjpIXMXJ.mjs → site-url-Cs_V9n3V.mjs} +3 -3
- package/dist/{site-url-DjpIXMXJ.mjs.map → site-url-Cs_V9n3V.mjs.map} +1 -1
- package/dist/{snapshot-BBlGkb2q.mjs → snapshot-DSB8P7Lm.mjs} +1 -1
- package/dist/{snapshot-BBlGkb2q.mjs.map → snapshot-DSB8P7Lm.mjs.map} +1 -1
- package/dist/{ssrf-Cpvg_n3A.mjs → ssrf-DqebVE34.mjs} +21 -5
- package/dist/{ssrf-Cpvg_n3A.mjs.map → ssrf-DqebVE34.mjs.map} +1 -1
- package/dist/{state-DYwPue40.mjs → state-BJfU9Uzw.mjs} +12 -4
- package/dist/state-BJfU9Uzw.mjs.map +1 -0
- package/dist/{status-CWVYpbD8.mjs → status-DDu8HIQl.mjs} +1 -1
- package/dist/{status-CWVYpbD8.mjs.map → status-DDu8HIQl.mjs.map} +1 -1
- package/dist/storage/local.d.mts +1 -1
- package/dist/storage/local.mjs +1 -1
- package/dist/storage/s3.d.mts +1 -1
- package/dist/storage/s3.mjs +1 -1
- package/dist/{target-DixqqV5i.mjs → target-D0o26Azo.mjs} +1 -1
- package/dist/{target-DixqqV5i.mjs.map → target-D0o26Azo.mjs.map} +1 -1
- package/dist/{taxonomies-OHUIiIpI.mjs → taxonomies-CPGxo-bn.mjs} +5 -5
- package/dist/{taxonomies-OHUIiIpI.mjs.map → taxonomies-CPGxo-bn.mjs.map} +1 -1
- package/dist/{taxonomies-BlrncHi9.mjs → taxonomies-kmyudNGP.mjs} +7 -7
- package/dist/{taxonomies-BlrncHi9.mjs.map → taxonomies-kmyudNGP.mjs.map} +1 -1
- package/dist/{taxonomy-BqCZ1TdU.mjs → taxonomy-8X09dLN5.mjs} +4 -4
- package/dist/{taxonomy-BqCZ1TdU.mjs.map → taxonomy-8X09dLN5.mjs.map} +1 -1
- package/dist/{tokens-C39klX8R.mjs → tokens-gTS-IVUp.mjs} +1 -1
- package/dist/{tokens-C39klX8R.mjs.map → tokens-gTS-IVUp.mjs.map} +1 -1
- package/dist/{transaction-NQj4VJ7Z.mjs → transaction-0KOpOyMu.mjs} +2 -1
- package/dist/{transaction-NQj4VJ7Z.mjs.map → transaction-0KOpOyMu.mjs.map} +1 -1
- package/dist/{transport-RQE36APG.d.mts → transport-_6R1ub7t.d.mts} +1 -1
- package/dist/{transport-RQE36APG.d.mts.map → transport-_6R1ub7t.d.mts.map} +1 -1
- package/dist/{transport-DBJwa-Si.mjs → transport-fX59xaJz.mjs} +4 -3
- package/dist/{transport-DBJwa-Si.mjs.map → transport-fX59xaJz.mjs.map} +1 -1
- package/dist/{trusted-proxy-CEVekpby.mjs → trusted-proxy-fe6nEgR4.mjs} +1 -1
- package/dist/{trusted-proxy-CEVekpby.mjs.map → trusted-proxy-fe6nEgR4.mjs.map} +1 -1
- package/dist/types-75KIqzL9.mjs.map +1 -1
- package/dist/{types-BW1syrlw.mjs → types-BXUmsINL.mjs} +1 -1
- package/dist/{types-BW1syrlw.mjs.map → types-BXUmsINL.mjs.map} +1 -1
- package/dist/{types-BntycPTF.d.mts → types-Blb-MRC3.d.mts} +1 -1
- package/dist/{types-BntycPTF.d.mts.map → types-Blb-MRC3.d.mts.map} +1 -1
- package/dist/{types-C2pMvO62.d.mts → types-Br-ERaxh.d.mts} +2 -1
- package/dist/types-Br-ERaxh.d.mts.map +1 -0
- package/dist/{types-DWRhk9xZ.d.mts → types-BzBd3PeX.d.mts} +1 -1
- package/dist/{types-DWRhk9xZ.d.mts.map → types-BzBd3PeX.d.mts.map} +1 -1
- package/dist/{types-CXnOzDe1.d.mts → types-CLqvnd05.d.mts} +1 -1
- package/dist/{types-CXnOzDe1.d.mts.map → types-CLqvnd05.d.mts.map} +1 -1
- package/dist/{types-Dfk8KI5R.d.mts → types-D5VVLr7J.d.mts} +1 -1
- package/dist/{types-Dfk8KI5R.d.mts.map → types-D5VVLr7J.d.mts.map} +1 -1
- package/dist/{types-DQIDRKF2.d.mts → types-DHxzBjbD.d.mts} +10 -1
- package/dist/types-DHxzBjbD.d.mts.map +1 -0
- package/dist/{types-DN64_zzZ.d.mts → types-DJQxln7q.d.mts} +3 -3
- package/dist/{types-DN64_zzZ.d.mts.map → types-DJQxln7q.d.mts.map} +1 -1
- package/dist/{types-CtzytVXn.mjs → types-DM3vioBY.mjs} +1 -1
- package/dist/{types-CtzytVXn.mjs.map → types-DM3vioBY.mjs.map} +1 -1
- package/dist/{types-BcqdcT-r.d.mts → types-D_DWe7k9.d.mts} +1 -1
- package/dist/{types-BcqdcT-r.d.mts.map → types-D_DWe7k9.d.mts.map} +1 -1
- package/dist/{types-DrJrVCT1.d.mts → types-Vg6f5i3s.d.mts} +3 -3
- package/dist/{types-DrJrVCT1.d.mts.map → types-Vg6f5i3s.d.mts.map} +1 -1
- package/dist/{upload-attempts-D4FS8LT6.mjs → upload-attempts-CNyGSepg.mjs} +1 -1
- package/dist/{upload-attempts-D4FS8LT6.mjs.map → upload-attempts-CNyGSepg.mjs.map} +1 -1
- package/dist/{url-pattern-BHS0V5Ng.mjs → url-pattern-K-KdXcSe.mjs} +1 -1
- package/dist/{url-pattern-BHS0V5Ng.mjs.map → url-pattern-K-KdXcSe.mjs.map} +1 -1
- package/dist/{user-DJZfUJVE.mjs → user-CtYY0tp2.mjs} +2 -2
- package/dist/{user-DJZfUJVE.mjs.map → user-CtYY0tp2.mjs.map} +1 -1
- package/dist/{utils-D4vD_Y98.mjs → utils-HztC73hq.mjs} +1 -1
- package/dist/{utils-D4vD_Y98.mjs.map → utils-HztC73hq.mjs.map} +1 -1
- package/dist/{validate-BMLBvxOC.mjs → validate-Dd-IUjnZ.mjs} +2 -2
- package/dist/{validate-BMLBvxOC.mjs.map → validate-Dd-IUjnZ.mjs.map} +1 -1
- package/dist/{validate-CTqt5nuE.d.mts → validate-DlqdOZXB.d.mts} +5 -5
- package/dist/{validate-CTqt5nuE.d.mts.map → validate-DlqdOZXB.d.mts.map} +1 -1
- package/dist/{validation-npvENUCB.mjs → validation-D83n7Npi.mjs} +10 -8
- package/dist/{validation-npvENUCB.mjs.map → validation-D83n7Npi.mjs.map} +1 -1
- package/dist/version-ri-sCyAp.mjs +7 -0
- package/dist/{version-DB_fqCSI.mjs.map → version-ri-sCyAp.mjs.map} +1 -1
- package/dist/{widgets-BD3ho7Rq.mjs → widgets-CpmZd9Q-.mjs} +4 -4
- package/dist/{widgets-BD3ho7Rq.mjs.map → widgets-CpmZd9Q-.mjs.map} +1 -1
- package/dist/{wxr-taxonomies-Ca68766D.d.mts → wxr-taxonomies-BFd0y72_.d.mts} +1 -1
- package/dist/{wxr-taxonomies-Ca68766D.d.mts.map → wxr-taxonomies-BFd0y72_.d.mts.map} +1 -1
- package/dist/{wxr-taxonomies-B1R3vBoD.mjs → wxr-taxonomies-Df4vxWcU.mjs} +4 -4
- package/dist/{wxr-taxonomies-B1R3vBoD.mjs.map → wxr-taxonomies-Df4vxWcU.mjs.map} +1 -1
- package/dist/{zod-generator-LC-on_Vb.mjs → zod-generator-DylzusHh.mjs} +24 -18
- package/dist/zod-generator-DylzusHh.mjs.map +1 -0
- package/package.json +16 -8
- package/src/api/errors.ts +20 -0
- package/src/api/handlers/index.ts +17 -0
- package/src/api/handlers/media-allowlist.ts +1 -0
- package/src/api/handlers/media-folders.ts +130 -0
- package/src/api/handlers/media-usage-activation.ts +102 -0
- package/src/api/handlers/media-usage.ts +108 -0
- package/src/api/handlers/media.ts +62 -2
- package/src/api/handlers/registry.ts +134 -316
- package/src/api/openapi/document.ts +192 -2
- package/src/api/schemas/media-usage.ts +77 -0
- package/src/api/schemas/media.ts +69 -0
- package/src/astro/integration/routes.ts +18 -0
- package/src/astro/integration/vite-config.ts +2 -7
- package/src/astro/middleware/auth.ts +4 -0
- package/src/astro/middleware.ts +0 -7
- package/src/astro/routes/api/admin/media-usage/activation.ts +42 -0
- package/src/astro/routes/api/admin/media-usage/progress.ts +37 -0
- package/src/astro/routes/api/admin/plugins/registry/artifact.ts +246 -96
- package/src/astro/routes/api/auth/me.ts +14 -2
- package/src/astro/routes/api/media/[id].ts +3 -0
- package/src/astro/routes/api/media/folders/[id].ts +55 -0
- package/src/astro/routes/api/media/folders/index.ts +37 -0
- package/src/astro/routes/api/media.ts +12 -2
- package/src/astro/routes/api/setup/dev-bypass.ts +12 -0
- package/src/astro/types.ts +11 -1
- package/src/client/index.ts +140 -2
- package/src/client/transport.ts +6 -2
- package/src/components/EmDashImage.astro +154 -50
- package/src/components/Gallery.astro +7 -0
- package/src/components/InlinePortableTextEditor.tsx +130 -1
- package/src/components/LiveSearch.astro +23 -0
- package/src/components/inline-code-block.tsx +180 -49
- package/src/content/converters/gallery.ts +2 -0
- package/src/content/converters/types.ts +2 -0
- package/src/database/connection.ts +2 -31
- package/src/database/index.ts +1 -1
- package/src/database/json-recordset.ts +16 -0
- package/src/database/migrations/019_i18n.ts +1 -1
- package/src/database/migrations/071_restore_content_bylines_table.ts +43 -0
- package/src/database/migrations/072_media_folders.ts +72 -0
- package/src/database/migrations/073_media_focal_point.ts +57 -0
- package/src/database/migrations/runner.ts +8 -2
- package/src/database/repositories/content.ts +5 -4
- package/src/database/repositories/media-folders.ts +115 -0
- package/src/database/repositories/media-usage-work.ts +395 -111
- package/src/database/repositories/media-usage.ts +1038 -10
- package/src/database/repositories/media.ts +97 -29
- package/src/database/transaction.ts +1 -0
- package/src/database/types.ts +13 -0
- package/src/db/adapters.ts +2 -2
- package/src/db/node-sqlite-compat.ts +78 -0
- package/src/db/sqlite.ts +3 -3
- package/src/emdash-runtime.ts +110 -105
- package/src/fields/image.ts +7 -1
- package/src/fields/types.ts +6 -2
- package/src/index.ts +5 -0
- package/src/media/focal-point.ts +37 -0
- package/src/media/local-runtime.ts +8 -0
- package/src/media/mime.ts +1 -0
- package/src/media/normalize.ts +10 -0
- package/src/media/types.ts +10 -0
- package/src/media/usage/activation.ts +162 -35
- package/src/media/usage/capture-triggers.ts +19 -3
- package/src/media/usage/collection-deletion-processor.ts +7 -3
- package/src/media/usage/collection-deletion.ts +10 -0
- package/src/media/usage/content-refresh.ts +258 -39
- package/src/media/usage/content-snapshots.ts +128 -31
- package/src/media/usage/extractor.ts +32 -13
- package/src/media/usage/maintenance-engine.ts +166 -0
- package/src/media/usage/reconciliation-processor.ts +106 -29
- package/src/media/usage/reconciliation.ts +90 -7
- package/src/media/usage/work-processor.ts +342 -101
- package/src/plugins/index.ts +1 -0
- package/src/plugins/save-rejection.ts +20 -0
- package/src/plugins/scheduler/node.ts +1 -13
- package/src/plugins/scheduler/types.ts +0 -2
- package/src/plugins/state.ts +13 -3
- package/src/registry/artifact-fetch.ts +530 -0
- package/src/registry/config.ts +24 -6
- package/src/registry/types.ts +12 -15
- package/src/schema/types.ts +1 -0
- package/src/schema/zod-generator.ts +12 -4
- package/src/security/ssrf.ts +21 -2
- package/src/seed/apply.ts +4 -4
- package/src/ui.ts +2 -0
- package/dist/api-BeBglVxU.mjs.map +0 -1
- package/dist/collection-deletion-DQPvMD8R.mjs.map +0 -1
- package/dist/content-ZHCc1ngN.mjs.map +0 -1
- package/dist/content-refresh-B_8SJzuU.mjs.map +0 -1
- package/dist/errors-CLUPm7aD.mjs.map +0 -1
- package/dist/index-BVBZj4-7.d.mts.map +0 -1
- package/dist/media-BWWWb8kg.mjs.map +0 -1
- package/dist/media-CzhAn2--.mjs.map +0 -1
- package/dist/media-allowlist-D6x-Us02.mjs.map +0 -1
- package/dist/media-usage-BZCydfvu.mjs.map +0 -1
- package/dist/media-usage-work-DrCbqBcl.mjs.map +0 -1
- package/dist/menus-DSo5QeW0.mjs.map +0 -1
- package/dist/mime-DfIVjNkr.mjs.map +0 -1
- package/dist/normalize-Bc-s_r-a.mjs.map +0 -1
- package/dist/placeholder-Dp0K3RkD.d.mts.map +0 -1
- package/dist/registry-Cqa2I749.mjs.map +0 -1
- package/dist/relations-BHo5A8Zf.d.mts.map +0 -1
- package/dist/runner-C1T11CfC.mjs.map +0 -1
- package/dist/state-DYwPue40.mjs.map +0 -1
- package/dist/types-C2pMvO62.d.mts.map +0 -1
- package/dist/types-DQIDRKF2.d.mts.map +0 -1
- package/dist/version-DB_fqCSI.mjs +0 -7
- package/dist/zod-generator-LC-on_Vb.mjs.map +0 -1
- /package/dist/{api-tokens-rIXC6LdE.mjs → api-tokens-B5NHLNUN.mjs} +0 -0
- /package/dist/{ssrf-DpXgKsna.mjs → ssrf-BPKzkm6O.mjs} +0 -0
- /package/dist/{types-CP1CflWf.mjs → types-D6OcIp2P.mjs} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"taxonomies-BlrncHi9.mjs","names":[],"sources":["../src/taxonomies/term-counts.ts","../src/taxonomies/index.ts"],"sourcesContent":["/**\n * Shared visible-usage counts for taxonomy terms (issue #581).\n *\n * `content_taxonomies` rows are written for every entry regardless of status\n * and are never pruned on unpublish/trash, so counting the pivot directly\n * inflates counts with drafts and soft-deleted entries. Every user-facing\n * count (public widget, single-term page, admin term list) must instead count\n * only entries that have completed publication:\n * `status = 'published'` AND `deleted_at IS NULL`.\n *\n * The public render path is latency-sensitive on D1, so per-collection counts\n * are combined with UNION ALL — one query per taxonomy, never one per\n * collection, split only where the backend caps compound-SELECT terms.\n */\n\nimport type { Kysely } from \"kysely\";\nimport { sql } from \"kysely\";\n\nimport { buildStatusCondition, compoundSelectLimit } from \"../database/dialect-helpers.js\";\nimport type { Database } from \"../database/types.js\";\nimport { validateIdentifier } from \"../database/validate.js\";\nimport { chunks } from \"../utils/chunks.js\";\nimport { isMissingTableError } from \"../utils/db-errors.js\";\n\ninterface CountRow {\n\ttaxonomy_id: string;\n\tcount: number | string | bigint;\n}\n\n/**\n * Per-collection count branch. `taxonomy_id` stores the term's\n * translation_group, so results are keyed by group (locale-independent) and\n * each assignment is counted once per content translation group. When a\n * locale is provided, only that group's matching content row contributes.\n *\n * Scoping to the taxonomy uses `translation_group IN (...)` rather than a\n * join on `taxonomies.id` — the anchor row (id == group) can be deleted while\n * sibling translations survive, and a plain join on `translation_group` would\n * multiply counts by the number of locales.\n *\n * CROSS JOIN with the join predicate in WHERE keeps stats-blind SQLite/D1 from\n * reordering content_taxonomies out of the outer position; it touches ec_* only\n * through the translation-group index. Postgres treats this as an ordinary\n * inner join and plans freely.\n */\nfunction collectionBranch(\n\tdb: Kysely<Database>,\n\ttaxonomyName: string,\n\tcollection: string,\n\tlocale?: string,\n): ReturnType<typeof sql> {\n\treturn sql`\n\t\tSELECT ct.taxonomy_id AS taxonomy_id, COUNT(DISTINCT e.translation_group) AS count\n\t\tFROM content_taxonomies AS ct\n\t\tCROSS JOIN ${sql.ref(`ec_${collection}`)} AS e\n\t\tWHERE e.translation_group = ct.entry_id\n\t\t\tAND ct.collection = ${collection}\n\t\t\tAND ct.taxonomy_id IN (SELECT translation_group FROM taxonomies WHERE name = ${taxonomyName})\n\t\t\t${locale ? sql`AND e.locale = ${locale}` : sql``}\n\t\t\tAND ${buildStatusCondition(db, \"published\", \"e\")}\n\t\t\tAND e.deleted_at IS NULL\n\t\tGROUP BY ct.taxonomy_id`;\n}\n\nasync function runCounts(\n\tdb: Kysely<Database>,\n\ttaxonomyName: string,\n\tcollections: string[],\n\tlocale?: string,\n): Promise<Map<string, number>> {\n\tconst branches = collections.map((collection) =>\n\t\tcollectionBranch(db, taxonomyName, collection, locale),\n\t);\n\tconst union = sql.join(branches, sql` UNION ALL `);\n\tconst result = await sql<CountRow>`\n\t\tSELECT taxonomy_id, SUM(count) AS count\n\t\tFROM (${union}) AS per_collection\n\t\tGROUP BY taxonomy_id`.execute(db);\n\n\tconst counts = new Map<string, number>();\n\tfor (const row of result.rows) counts.set(row.taxonomy_id, Number(row.count));\n\treturn counts;\n}\n\nfunction addCounts(into: Map<string, number>, from: Map<string, number>): void {\n\tfor (const [group, count] of from) into.set(group, (into.get(group) ?? 0) + count);\n}\n\n/**\n * Counts for one batch of collections, degrading to a query per collection\n * when a declared collection has no ec_* table so the rest still contribute.\n */\nasync function runBatch(\n\tdb: Kysely<Database>,\n\ttaxonomyName: string,\n\tcollections: string[],\n\tlocale?: string,\n): Promise<Map<string, number>> {\n\ttry {\n\t\treturn await runCounts(db, taxonomyName, collections, locale);\n\t} catch (error) {\n\t\tif (!isMissingTableError(error)) throw error;\n\t}\n\n\tconst counts = new Map<string, number>();\n\tfor (const collection of collections) {\n\t\ttry {\n\t\t\taddCounts(counts, await runCounts(db, taxonomyName, [collection], locale));\n\t\t} catch (error) {\n\t\t\tif (!isMissingTableError(error)) throw error;\n\t\t}\n\t}\n\treturn counts;\n}\n\n/**\n * Count publicly-visible term assignments for one taxonomy, keyed by the\n * term's translation_group (what `content_taxonomies.taxonomy_id` stores).\n * When `locale` is provided, only entries in that locale contribute. Omitting\n * it preserves the locale-agnostic API used by legacy callers.\n *\n * Counts are scoped to the taxonomy's declared collections — pass\n * `TaxonomyDef.collections` (`_emdash_taxonomy_defs.collections`). Collections\n * whose `ec_*` table doesn't exist (pre-migration drift, a declared collection\n * that was never created) are skipped, yielding a partial-but-correct count\n * rather than a throw.\n *\n * One database round-trip for the whole taxonomy (UNION ALL across\n * collections). On a backend that caps compound-SELECT terms — D1 allows five\n * — the branches are split into one statement per batch, since a taxonomy\n * declaring more collections than that would otherwise take down every path\n * that shows counts. Per-collection sums are commutative, so batching cannot\n * change the total.\n *\n * Callers on the public render path should go through the request-cached\n * wrapper in `taxonomies/index.ts` so a page rendering both the widget and a\n * term detail shares one computation.\n */\nexport async function fetchVisibleTermCounts(\n\tdb: Kysely<Database>,\n\ttaxonomyName: string,\n\tcollections: string[],\n\tlocale?: string,\n): Promise<Map<string, number>> {\n\tconst unique = [...new Set(collections)];\n\tfor (const collection of unique) validateIdentifier(collection, \"collection slug\");\n\tif (unique.length === 0) return new Map();\n\n\tconst limit = compoundSelectLimit(db);\n\tconst batched = limit === null ? [unique] : chunks(unique, limit);\n\tconst batches = await Promise.all(\n\t\tbatched.map((batch) => runBatch(db, taxonomyName, batch, locale)),\n\t);\n\n\tconst counts = new Map<string, number>();\n\tfor (const batch of batches) addCounts(counts, batch);\n\treturn counts;\n}\n","/**\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), and `entry_id` stores the content translation_group, one\n * assignment resolves to the requested locale on both sides.\n */\n\nimport { sql, type Kysely } from \"kysely\";\n\nimport type { Database } from \"../database/types.js\";\nimport { validateIdentifier } from \"../database/validate.js\";\nimport { getI18nConfig } from \"../i18n/config.js\";\nimport { resolveLocale, resolveLocaleChain } from \"../i18n/resolve.js\";\nimport { getDb, resetTaxonomyNamesCache } from \"../loader.js\";\nimport {\n\tcachedQuery,\n\tCacheNamespace,\n\tcontentCacheNamespaces,\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 { fetchVisibleTermCounts } from \"./term-counts.js\";\nimport type { TaxonomyDef, TaxonomyTerm, TaxonomyTermRow } from \"./types.js\";\n\nexport interface TaxonomyQueryOptions {\n\tlocale?: string;\n}\n\nexport interface TaxonomyTermsOptions extends TaxonomyQueryOptions {\n\t/**\n\t * Populate each term's `count`. Counts aggregate the whole\n\t * `content_taxonomies` pivot against every declared collection, so callers\n\t * that don't render a count should opt out. Defaults to `true`.\n\t */\n\tincludeCounts?: boolean;\n}\n\ninterface EntryTermRow {\n\tentry_id: string;\n\tid: string;\n\tname: string;\n\tslug: string;\n\tlabel: string;\n\tparent_id: string | null;\n\tlocale: string;\n\ttranslation_group: string | null;\n}\n\nasync function selectEntryTermRows(\n\tdb: Kysely<Database>,\n\tcollection: string,\n\tentryIds: string[],\n\ttaxonomyName?: string,\n\tlocale?: string,\n): Promise<EntryTermRow[]> {\n\tvalidateIdentifier(collection, \"collection slug\");\n\tconst tableName = `ec_${collection}`;\n\tconst preferredLocale = locale ? sql`${locale}` : sql`content.locale`;\n\tconst defaultLocale = getI18nConfig()?.defaultLocale ?? \"en\";\n\tconst result = await sql<EntryTermRow>`\n\t\tSELECT content.id AS entry_id,\n\t\t\tcoalesce(exact_term.id, default_term.id) AS id,\n\t\t\tcoalesce(exact_term.name, default_term.name) AS name,\n\t\t\tcoalesce(exact_term.slug, default_term.slug) AS slug,\n\t\t\tcoalesce(exact_term.label, default_term.label) AS label,\n\t\t\tcoalesce(exact_term.parent_id, default_term.parent_id) AS parent_id,\n\t\t\tcoalesce(exact_term.locale, default_term.locale) AS locale,\n\t\t\tcoalesce(exact_term.translation_group, default_term.translation_group) AS translation_group\n\t\tFROM ${sql.ref(tableName)} AS content\n\t\tINNER JOIN content_taxonomies AS pivot\n\t\t\tON pivot.entry_id = content.translation_group\n\t\t\tAND pivot.collection = ${collection}\n\t\tLEFT JOIN taxonomies AS exact_term\n\t\t\tON exact_term.translation_group = pivot.taxonomy_id\n\t\t\tAND exact_term.locale = ${preferredLocale}\n\t\tLEFT JOIN taxonomies AS default_term\n\t\t\tON default_term.translation_group = pivot.taxonomy_id\n\t\t\tAND default_term.locale = ${defaultLocale}\n\t\tWHERE content.id IN (${sql.join(entryIds.map((id) => sql`${id}`))})\n\t\t\tAND coalesce(exact_term.id, default_term.id) IS NOT NULL\n\t\t\t${taxonomyName ? sql`AND coalesce(exact_term.name, default_term.name) = ${taxonomyName}` : sql``}\n\t\tORDER BY coalesce(exact_term.label, default_term.label) ASC\n\t`.execute(db);\n\treturn result.rows;\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 written only by the admin API and by\n * seed application. Caching them across the isolate lifetime drops the\n * per-render `SELECT * FROM _emdash_taxonomy_defs` 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`/`Update`/`Delete`, seed application). Other isolates\n * refresh on their 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 * Object-cache namespaces for values that embed visible term counts: the\n * taxonomy epoch (term/assignment writes) plus each counted collection's\n * content epoch, so publishing, unpublishing, or trashing an entry\n * invalidates the cached count promptly. Both content namespace generations\n * participate so rolling deployments preserve invalidation in either direction.\n */\nfunction termCountNamespaces(collections: string[]): string[] {\n\treturn [\n\t\t...[...new Set(collections)].flatMap((collection) => contentCacheNamespaces(collection)),\n\t\tCacheNamespace.TAXONOMIES,\n\t];\n}\n\n/**\n * All terms of a taxonomy in a specific locale (flat for non-hierarchical,\n * tree for hierarchical).\n *\n * The term list and the visible-entry counts are loaded and cached separately:\n * the list depends only on the taxonomy epoch, while the counts additionally\n * depend on every counted collection's content epoch and cost an aggregate over\n * the whole assignment pivot. Callers that don't render counts pass\n * `includeCounts: false` and skip that aggregate entirely, while still sharing\n * the term list with callers that do.\n */\nexport async function getTaxonomyTerms(\n\ttaxonomyName: string,\n\toptions: TaxonomyTermsOptions = {},\n): Promise<TaxonomyTerm[]> {\n\tconst locale = resolveLocale(options.locale);\n\tconst def = await getTaxonomyDef(taxonomyName, options);\n\tif (!def) return [];\n\tif (options.includeCounts === false) return getTermList(def, locale);\n\n\t// The two are independent, so run them concurrently to save a round trip.\n\tconst [terms, counts] = await Promise.all([\n\t\tgetTermList(def, locale),\n\t\tgetVisibleTermCounts(def.name, def.collections, locale),\n\t]);\n\treturn withCounts(terms, counts);\n}\n\n/** Terms without counts, under the cache keys the layout prefetch warms. */\nfunction getTermList(def: TaxonomyDef, locale: string | undefined): Promise<TaxonomyTerm[]> {\n\tconst localeKey = locale ?? \"*\";\n\treturn requestCached(`taxonomy-terms:${def.name}:${localeKey}`, () =>\n\t\tcachedQuery({\n\t\t\tnamespace: CacheNamespace.TAXONOMIES,\n\t\t\tkey: `termList:${def.name}:${localeKey}`,\n\t\t\tload: () => loadTaxonomyTerms(def, locale),\n\t\t}),\n\t);\n}\n\n/**\n * Copy a term list with counts attached. Counts are keyed by translation_group\n * (what the pivot stores) and are locale-independent. Rebuilds every node so\n * the shared, cached count-free list is never mutated.\n */\nfunction withCounts(terms: TaxonomyTerm[], counts: Map<string, number>): TaxonomyTerm[] {\n\treturn terms.map((term) => ({\n\t\t...term,\n\t\tcount: counts.get(term.translationGroup ?? term.id) ?? 0,\n\t\tchildren: withCounts(term.children, counts),\n\t}));\n}\n\nasync function loadTaxonomyTerms(\n\tdef: TaxonomyDef,\n\tlocale: string | undefined,\n): Promise<TaxonomyTerm[]> {\n\tconst db = await getDb();\n\n\tlet termsQuery = db\n\t\t.selectFrom(\"taxonomies\")\n\t\t.selectAll()\n\t\t.where(\"name\", \"=\", def.name)\n\t\t.orderBy(\"sort_order\", \"asc\")\n\t\t.orderBy(\"label\", \"asc\");\n\tif (locale !== undefined) termsQuery = termsQuery.where(\"locale\", \"=\", locale);\n\n\tconst rows = await termsQuery.execute();\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);\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\tlocale: term.locale,\n\t\ttranslationGroup: term.translation_group,\n\t}));\n}\n\n/**\n * Per-translation-group visible-usage counts for one taxonomy, in a single\n * round-trip (see `fetchVisibleTermCounts`). The pivot identity is the\n * translation group, while entry rows are scoped to the resolved locale.\n * Request and object cache keys include that locale so translated views never\n * reuse each other's visible counts.\n */\nfunction getVisibleTermCounts(\n\ttaxonomyName: string,\n\tcollections: string[],\n\tlocale?: string,\n): Promise<Map<string, number>> {\n\t// The collection scope is part of the key: per-locale rows of the same def\n\t// can drift in their declared collections, and a caller may pass a narrower\n\t// scope. Identical inputs (the widget + term-page hot path) still share one\n\t// entry.\n\tconst scope = [...new Set(collections)].toSorted().join(\",\");\n\tconst localeScope = locale ?? \"*\";\n\treturn requestCached(`taxonomy-term-counts:${taxonomyName}:${scope}:${localeScope}`, async () => {\n\t\t// A Map is not JSON-representable — cache the entries, rebuild on read.\n\t\tconst entries = await cachedQuery({\n\t\t\tnamespace: termCountNamespaces(collections),\n\t\t\tkey: `termCounts:${taxonomyName}:${scope}:${localeScope}`,\n\t\t\tload: async (): Promise<Array<[string, number]>> => {\n\t\t\t\tconst db = await getDb();\n\t\t\t\treturn [...(await fetchVisibleTermCounts(db, taxonomyName, collections, locale))];\n\t\t\t},\n\t\t});\n\t\treturn new Map(entries);\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// The def supplies the collections the visible count is scoped to. It is\n\t// resolved before cachedQuery so the entry lives under each collection's\n\t// content namespace — publishing or unpublishing an entry invalidates the\n\t// embedded count (see termCountNamespaces).\n\tconst def = await getTaxonomyDef(taxonomyName, options);\n\tconst collections = def?.collections ?? [];\n\treturn cachedQuery({\n\t\tnamespace: termCountNamespaces(collections),\n\t\tkey: `term:${taxonomyName}:${slug}:${chain.join(\",\")}`,\n\t\tload: () => loadTerm(taxonomyName, slug, chain, collections),\n\t});\n}\n\nasync function loadTerm(\n\ttaxonomyName: string,\n\tslug: string,\n\tchain: string[],\n\tcollections: 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(\"sort_order\", \"asc\")\n\t\t.orderBy(\"label\", \"asc\");\n\tconst termLocale = row.locale;\n\tif (termLocale) childrenQuery = childrenQuery.where(\"locale\", \"=\", termLocale);\n\n\t// The visible-usage counts and children queries both depend only on the\n\t// term row, so run them concurrently to save a round trip on remote\n\t// databases. The counts map is request-cached per taxonomy — on a page\n\t// that also renders the taxonomy widget it's a free Map lookup.\n\tconst [counts, childRows] = await Promise.all([\n\t\tgetVisibleTermCounts(taxonomyName, collections, chain[0] ?? row.locale),\n\t\tchildrenQuery.execute(),\n\t]);\n\tconst count = counts.get(row.translation_group ?? row.id) ?? 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 and then\n * the configured default locale.\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: [...contentCacheNamespaces(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\t\t\t\t\tconst rows = await selectEntryTermRows(db, collection, [entryId], taxonomyName, locale);\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\trows = await selectEntryTermRows(db, collection, chunk, taxonomyName, locale);\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: [...contentCacheNamespaces(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\trows = await selectEntryTermRows(db, collection, chunk, undefined, locale);\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[]): 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\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6CA,SAAS,iBACR,IACA,cACA,YACA,QACyB;AACzB,QAAO,GAAG;;;eAGI,IAAI,IAAI,MAAM,aAAa,CAAC;;yBAElB,WAAW;kFAC8C,aAAa;KAC1F,SAAS,GAAG,kBAAkB,WAAW,GAAG,GAAG;SAC3C,qBAAqB,IAAI,aAAa,IAAI,CAAC;;;;AAKpD,eAAe,UACd,IACA,cACA,aACA,QAC+B;CAC/B,MAAM,WAAW,YAAY,KAAK,eACjC,iBAAiB,IAAI,cAAc,YAAY,OAAO,CACtD;CAED,MAAM,SAAS,MAAM,GAAa;;UADpB,IAAI,KAAK,UAAU,GAAG,cAAc,CAGnC;wBACQ,QAAQ,GAAG;CAElC,MAAM,yBAAS,IAAI,KAAqB;AACxC,MAAK,MAAM,OAAO,OAAO,KAAM,QAAO,IAAI,IAAI,aAAa,OAAO,IAAI,MAAM,CAAC;AAC7E,QAAO;;AAGR,SAAS,UAAU,MAA2B,MAAiC;AAC9E,MAAK,MAAM,CAAC,OAAO,UAAU,KAAM,MAAK,IAAI,QAAQ,KAAK,IAAI,MAAM,IAAI,KAAK,MAAM;;;;;;AAOnF,eAAe,SACd,IACA,cACA,aACA,QAC+B;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,kBAAkB,IAAI;EACtB;;;;;AAMF,SAAS,UAAU,WAA8C;CAKhE,MAAM,gCAAgB,IAAI,KAA2B;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,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-kmyudNGP.mjs","names":[],"sources":["../src/taxonomies/term-counts.ts","../src/taxonomies/index.ts"],"sourcesContent":["/**\n * Shared visible-usage counts for taxonomy terms (issue #581).\n *\n * `content_taxonomies` rows are written for every entry regardless of status\n * and are never pruned on unpublish/trash, so counting the pivot directly\n * inflates counts with drafts and soft-deleted entries. Every user-facing\n * count (public widget, single-term page, admin term list) must instead count\n * only entries that have completed publication:\n * `status = 'published'` AND `deleted_at IS NULL`.\n *\n * The public render path is latency-sensitive on D1, so per-collection counts\n * are combined with UNION ALL — one query per taxonomy, never one per\n * collection, split only where the backend caps compound-SELECT terms.\n */\n\nimport type { Kysely } from \"kysely\";\nimport { sql } from \"kysely\";\n\nimport { buildStatusCondition, compoundSelectLimit } from \"../database/dialect-helpers.js\";\nimport type { Database } from \"../database/types.js\";\nimport { validateIdentifier } from \"../database/validate.js\";\nimport { chunks } from \"../utils/chunks.js\";\nimport { isMissingTableError } from \"../utils/db-errors.js\";\n\ninterface CountRow {\n\ttaxonomy_id: string;\n\tcount: number | string | bigint;\n}\n\n/**\n * Per-collection count branch. `taxonomy_id` stores the term's\n * translation_group, so results are keyed by group (locale-independent) and\n * each assignment is counted once per content translation group. When a\n * locale is provided, only that group's matching content row contributes.\n *\n * Scoping to the taxonomy uses `translation_group IN (...)` rather than a\n * join on `taxonomies.id` — the anchor row (id == group) can be deleted while\n * sibling translations survive, and a plain join on `translation_group` would\n * multiply counts by the number of locales.\n *\n * CROSS JOIN with the join predicate in WHERE keeps stats-blind SQLite/D1 from\n * reordering content_taxonomies out of the outer position; it touches ec_* only\n * through the translation-group index. Postgres treats this as an ordinary\n * inner join and plans freely.\n */\nfunction collectionBranch(\n\tdb: Kysely<Database>,\n\ttaxonomyName: string,\n\tcollection: string,\n\tlocale?: string,\n): ReturnType<typeof sql> {\n\treturn sql`\n\t\tSELECT ct.taxonomy_id AS taxonomy_id, COUNT(DISTINCT e.translation_group) AS count\n\t\tFROM content_taxonomies AS ct\n\t\tCROSS JOIN ${sql.ref(`ec_${collection}`)} AS e\n\t\tWHERE e.translation_group = ct.entry_id\n\t\t\tAND ct.collection = ${collection}\n\t\t\tAND ct.taxonomy_id IN (SELECT translation_group FROM taxonomies WHERE name = ${taxonomyName})\n\t\t\t${locale ? sql`AND e.locale = ${locale}` : sql``}\n\t\t\tAND ${buildStatusCondition(db, \"published\", \"e\")}\n\t\t\tAND e.deleted_at IS NULL\n\t\tGROUP BY ct.taxonomy_id`;\n}\n\nasync function runCounts(\n\tdb: Kysely<Database>,\n\ttaxonomyName: string,\n\tcollections: string[],\n\tlocale?: string,\n): Promise<Map<string, number>> {\n\tconst branches = collections.map((collection) =>\n\t\tcollectionBranch(db, taxonomyName, collection, locale),\n\t);\n\tconst union = sql.join(branches, sql` UNION ALL `);\n\tconst result = await sql<CountRow>`\n\t\tSELECT taxonomy_id, SUM(count) AS count\n\t\tFROM (${union}) AS per_collection\n\t\tGROUP BY taxonomy_id`.execute(db);\n\n\tconst counts = new Map<string, number>();\n\tfor (const row of result.rows) counts.set(row.taxonomy_id, Number(row.count));\n\treturn counts;\n}\n\nfunction addCounts(into: Map<string, number>, from: Map<string, number>): void {\n\tfor (const [group, count] of from) into.set(group, (into.get(group) ?? 0) + count);\n}\n\n/**\n * Counts for one batch of collections, degrading to a query per collection\n * when a declared collection has no ec_* table so the rest still contribute.\n */\nasync function runBatch(\n\tdb: Kysely<Database>,\n\ttaxonomyName: string,\n\tcollections: string[],\n\tlocale?: string,\n): Promise<Map<string, number>> {\n\ttry {\n\t\treturn await runCounts(db, taxonomyName, collections, locale);\n\t} catch (error) {\n\t\tif (!isMissingTableError(error)) throw error;\n\t}\n\n\tconst counts = new Map<string, number>();\n\tfor (const collection of collections) {\n\t\ttry {\n\t\t\taddCounts(counts, await runCounts(db, taxonomyName, [collection], locale));\n\t\t} catch (error) {\n\t\t\tif (!isMissingTableError(error)) throw error;\n\t\t}\n\t}\n\treturn counts;\n}\n\n/**\n * Count publicly-visible term assignments for one taxonomy, keyed by the\n * term's translation_group (what `content_taxonomies.taxonomy_id` stores).\n * When `locale` is provided, only entries in that locale contribute. Omitting\n * it preserves the locale-agnostic API used by legacy callers.\n *\n * Counts are scoped to the taxonomy's declared collections — pass\n * `TaxonomyDef.collections` (`_emdash_taxonomy_defs.collections`). Collections\n * whose `ec_*` table doesn't exist (pre-migration drift, a declared collection\n * that was never created) are skipped, yielding a partial-but-correct count\n * rather than a throw.\n *\n * One database round-trip for the whole taxonomy (UNION ALL across\n * collections). On a backend that caps compound-SELECT terms — D1 allows five\n * — the branches are split into one statement per batch, since a taxonomy\n * declaring more collections than that would otherwise take down every path\n * that shows counts. Per-collection sums are commutative, so batching cannot\n * change the total.\n *\n * Callers on the public render path should go through the request-cached\n * wrapper in `taxonomies/index.ts` so a page rendering both the widget and a\n * term detail shares one computation.\n */\nexport async function fetchVisibleTermCounts(\n\tdb: Kysely<Database>,\n\ttaxonomyName: string,\n\tcollections: string[],\n\tlocale?: string,\n): Promise<Map<string, number>> {\n\tconst unique = [...new Set(collections)];\n\tfor (const collection of unique) validateIdentifier(collection, \"collection slug\");\n\tif (unique.length === 0) return new Map();\n\n\tconst limit = compoundSelectLimit(db);\n\tconst batched = limit === null ? [unique] : chunks(unique, limit);\n\tconst batches = await Promise.all(\n\t\tbatched.map((batch) => runBatch(db, taxonomyName, batch, locale)),\n\t);\n\n\tconst counts = new Map<string, number>();\n\tfor (const batch of batches) addCounts(counts, batch);\n\treturn counts;\n}\n","/**\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), and `entry_id` stores the content translation_group, one\n * assignment resolves to the requested locale on both sides.\n */\n\nimport { sql, type Kysely } from \"kysely\";\n\nimport type { Database } from \"../database/types.js\";\nimport { validateIdentifier } from \"../database/validate.js\";\nimport { getI18nConfig } from \"../i18n/config.js\";\nimport { resolveLocale, resolveLocaleChain } from \"../i18n/resolve.js\";\nimport { getDb, resetTaxonomyNamesCache } from \"../loader.js\";\nimport {\n\tcachedQuery,\n\tCacheNamespace,\n\tcontentCacheNamespaces,\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 { fetchVisibleTermCounts } from \"./term-counts.js\";\nimport type { TaxonomyDef, TaxonomyTerm, TaxonomyTermRow } from \"./types.js\";\n\nexport interface TaxonomyQueryOptions {\n\tlocale?: string;\n}\n\nexport interface TaxonomyTermsOptions extends TaxonomyQueryOptions {\n\t/**\n\t * Populate each term's `count`. Counts aggregate the whole\n\t * `content_taxonomies` pivot against every declared collection, so callers\n\t * that don't render a count should opt out. Defaults to `true`.\n\t */\n\tincludeCounts?: boolean;\n}\n\ninterface EntryTermRow {\n\tentry_id: string;\n\tid: string;\n\tname: string;\n\tslug: string;\n\tlabel: string;\n\tparent_id: string | null;\n\tlocale: string;\n\ttranslation_group: string | null;\n}\n\nasync function selectEntryTermRows(\n\tdb: Kysely<Database>,\n\tcollection: string,\n\tentryIds: string[],\n\ttaxonomyName?: string,\n\tlocale?: string,\n): Promise<EntryTermRow[]> {\n\tvalidateIdentifier(collection, \"collection slug\");\n\tconst tableName = `ec_${collection}`;\n\tconst preferredLocale = locale ? sql`${locale}` : sql`content.locale`;\n\tconst defaultLocale = getI18nConfig()?.defaultLocale ?? \"en\";\n\tconst result = await sql<EntryTermRow>`\n\t\tSELECT content.id AS entry_id,\n\t\t\tcoalesce(exact_term.id, default_term.id) AS id,\n\t\t\tcoalesce(exact_term.name, default_term.name) AS name,\n\t\t\tcoalesce(exact_term.slug, default_term.slug) AS slug,\n\t\t\tcoalesce(exact_term.label, default_term.label) AS label,\n\t\t\tcoalesce(exact_term.parent_id, default_term.parent_id) AS parent_id,\n\t\t\tcoalesce(exact_term.locale, default_term.locale) AS locale,\n\t\t\tcoalesce(exact_term.translation_group, default_term.translation_group) AS translation_group\n\t\tFROM ${sql.ref(tableName)} AS content\n\t\tINNER JOIN content_taxonomies AS pivot\n\t\t\tON pivot.entry_id = content.translation_group\n\t\t\tAND pivot.collection = ${collection}\n\t\tLEFT JOIN taxonomies AS exact_term\n\t\t\tON exact_term.translation_group = pivot.taxonomy_id\n\t\t\tAND exact_term.locale = ${preferredLocale}\n\t\tLEFT JOIN taxonomies AS default_term\n\t\t\tON default_term.translation_group = pivot.taxonomy_id\n\t\t\tAND default_term.locale = ${defaultLocale}\n\t\tWHERE content.id IN (${sql.join(entryIds.map((id) => sql`${id}`))})\n\t\t\tAND coalesce(exact_term.id, default_term.id) IS NOT NULL\n\t\t\t${taxonomyName ? sql`AND coalesce(exact_term.name, default_term.name) = ${taxonomyName}` : sql``}\n\t\tORDER BY coalesce(exact_term.label, default_term.label) ASC\n\t`.execute(db);\n\treturn result.rows;\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 written only by the admin API and by\n * seed application. Caching them across the isolate lifetime drops the\n * per-render `SELECT * FROM _emdash_taxonomy_defs` 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`/`Update`/`Delete`, seed application). Other isolates\n * refresh on their 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 * Object-cache namespaces for values that embed visible term counts: the\n * taxonomy epoch (term/assignment writes) plus each counted collection's\n * content epoch, so publishing, unpublishing, or trashing an entry\n * invalidates the cached count promptly. Both content namespace generations\n * participate so rolling deployments preserve invalidation in either direction.\n */\nfunction termCountNamespaces(collections: string[]): string[] {\n\treturn [\n\t\t...[...new Set(collections)].flatMap((collection) => contentCacheNamespaces(collection)),\n\t\tCacheNamespace.TAXONOMIES,\n\t];\n}\n\n/**\n * All terms of a taxonomy in a specific locale (flat for non-hierarchical,\n * tree for hierarchical).\n *\n * The term list and the visible-entry counts are loaded and cached separately:\n * the list depends only on the taxonomy epoch, while the counts additionally\n * depend on every counted collection's content epoch and cost an aggregate over\n * the whole assignment pivot. Callers that don't render counts pass\n * `includeCounts: false` and skip that aggregate entirely, while still sharing\n * the term list with callers that do.\n */\nexport async function getTaxonomyTerms(\n\ttaxonomyName: string,\n\toptions: TaxonomyTermsOptions = {},\n): Promise<TaxonomyTerm[]> {\n\tconst locale = resolveLocale(options.locale);\n\tconst def = await getTaxonomyDef(taxonomyName, options);\n\tif (!def) return [];\n\tif (options.includeCounts === false) return getTermList(def, locale);\n\n\t// The two are independent, so run them concurrently to save a round trip.\n\tconst [terms, counts] = await Promise.all([\n\t\tgetTermList(def, locale),\n\t\tgetVisibleTermCounts(def.name, def.collections, locale),\n\t]);\n\treturn withCounts(terms, counts);\n}\n\n/** Terms without counts, under the cache keys the layout prefetch warms. */\nfunction getTermList(def: TaxonomyDef, locale: string | undefined): Promise<TaxonomyTerm[]> {\n\tconst localeKey = locale ?? \"*\";\n\treturn requestCached(`taxonomy-terms:${def.name}:${localeKey}`, () =>\n\t\tcachedQuery({\n\t\t\tnamespace: CacheNamespace.TAXONOMIES,\n\t\t\tkey: `termList:${def.name}:${localeKey}`,\n\t\t\tload: () => loadTaxonomyTerms(def, locale),\n\t\t}),\n\t);\n}\n\n/**\n * Copy a term list with counts attached. Counts are keyed by translation_group\n * (what the pivot stores) and are locale-independent. Rebuilds every node so\n * the shared, cached count-free list is never mutated.\n */\nfunction withCounts(terms: TaxonomyTerm[], counts: Map<string, number>): TaxonomyTerm[] {\n\treturn terms.map((term) => ({\n\t\t...term,\n\t\tcount: counts.get(term.translationGroup ?? term.id) ?? 0,\n\t\tchildren: withCounts(term.children, counts),\n\t}));\n}\n\nasync function loadTaxonomyTerms(\n\tdef: TaxonomyDef,\n\tlocale: string | undefined,\n): Promise<TaxonomyTerm[]> {\n\tconst db = await getDb();\n\n\tlet termsQuery = db\n\t\t.selectFrom(\"taxonomies\")\n\t\t.selectAll()\n\t\t.where(\"name\", \"=\", def.name)\n\t\t.orderBy(\"sort_order\", \"asc\")\n\t\t.orderBy(\"label\", \"asc\");\n\tif (locale !== undefined) termsQuery = termsQuery.where(\"locale\", \"=\", locale);\n\n\tconst rows = await termsQuery.execute();\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);\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\tlocale: term.locale,\n\t\ttranslationGroup: term.translation_group,\n\t}));\n}\n\n/**\n * Per-translation-group visible-usage counts for one taxonomy, in a single\n * round-trip (see `fetchVisibleTermCounts`). The pivot identity is the\n * translation group, while entry rows are scoped to the resolved locale.\n * Request and object cache keys include that locale so translated views never\n * reuse each other's visible counts.\n */\nfunction getVisibleTermCounts(\n\ttaxonomyName: string,\n\tcollections: string[],\n\tlocale?: string,\n): Promise<Map<string, number>> {\n\t// The collection scope is part of the key: per-locale rows of the same def\n\t// can drift in their declared collections, and a caller may pass a narrower\n\t// scope. Identical inputs (the widget + term-page hot path) still share one\n\t// entry.\n\tconst scope = [...new Set(collections)].toSorted().join(\",\");\n\tconst localeScope = locale ?? \"*\";\n\treturn requestCached(`taxonomy-term-counts:${taxonomyName}:${scope}:${localeScope}`, async () => {\n\t\t// A Map is not JSON-representable — cache the entries, rebuild on read.\n\t\tconst entries = await cachedQuery({\n\t\t\tnamespace: termCountNamespaces(collections),\n\t\t\tkey: `termCounts:${taxonomyName}:${scope}:${localeScope}`,\n\t\t\tload: async (): Promise<Array<[string, number]>> => {\n\t\t\t\tconst db = await getDb();\n\t\t\t\treturn [...(await fetchVisibleTermCounts(db, taxonomyName, collections, locale))];\n\t\t\t},\n\t\t});\n\t\treturn new Map(entries);\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// The def supplies the collections the visible count is scoped to. It is\n\t// resolved before cachedQuery so the entry lives under each collection's\n\t// content namespace — publishing or unpublishing an entry invalidates the\n\t// embedded count (see termCountNamespaces).\n\tconst def = await getTaxonomyDef(taxonomyName, options);\n\tconst collections = def?.collections ?? [];\n\treturn cachedQuery({\n\t\tnamespace: termCountNamespaces(collections),\n\t\tkey: `term:${taxonomyName}:${slug}:${chain.join(\",\")}`,\n\t\tload: () => loadTerm(taxonomyName, slug, chain, collections),\n\t});\n}\n\nasync function loadTerm(\n\ttaxonomyName: string,\n\tslug: string,\n\tchain: string[],\n\tcollections: 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(\"sort_order\", \"asc\")\n\t\t.orderBy(\"label\", \"asc\");\n\tconst termLocale = row.locale;\n\tif (termLocale) childrenQuery = childrenQuery.where(\"locale\", \"=\", termLocale);\n\n\t// The visible-usage counts and children queries both depend only on the\n\t// term row, so run them concurrently to save a round trip on remote\n\t// databases. The counts map is request-cached per taxonomy — on a page\n\t// that also renders the taxonomy widget it's a free Map lookup.\n\tconst [counts, childRows] = await Promise.all([\n\t\tgetVisibleTermCounts(taxonomyName, collections, chain[0] ?? row.locale),\n\t\tchildrenQuery.execute(),\n\t]);\n\tconst count = counts.get(row.translation_group ?? row.id) ?? 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 and then\n * the configured default locale.\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: [...contentCacheNamespaces(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\t\t\t\t\tconst rows = await selectEntryTermRows(db, collection, [entryId], taxonomyName, locale);\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\trows = await selectEntryTermRows(db, collection, chunk, taxonomyName, locale);\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: [...contentCacheNamespaces(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\trows = await selectEntryTermRows(db, collection, chunk, undefined, locale);\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[]): 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\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6CA,SAAS,iBACR,IACA,cACA,YACA,QACyB;AACzB,QAAO,GAAG;;;eAGI,IAAI,IAAI,MAAM,aAAa,CAAC;;yBAElB,WAAW;kFAC8C,aAAa;KAC1F,SAAS,GAAG,kBAAkB,WAAW,GAAG,GAAG;SAC3C,qBAAqB,IAAI,aAAa,IAAI,CAAC;;;;AAKpD,eAAe,UACd,IACA,cACA,aACA,QAC+B;CAC/B,MAAM,WAAW,YAAY,KAAK,eACjC,iBAAiB,IAAI,cAAc,YAAY,OAAO,CACtD;CAED,MAAM,SAAS,MAAM,GAAa;;UADpB,IAAI,KAAK,UAAU,GAAG,cAAc,CAGnC;wBACQ,QAAQ,GAAG;CAElC,MAAM,yBAAS,IAAI,KAAqB;AACxC,MAAK,MAAM,OAAO,OAAO,KAAM,QAAO,IAAI,IAAI,aAAa,OAAO,IAAI,MAAM,CAAC;AAC7E,QAAO;;AAGR,SAAS,UAAU,MAA2B,MAAiC;AAC9E,MAAK,MAAM,CAAC,OAAO,UAAU,KAAM,MAAK,IAAI,QAAQ,KAAK,IAAI,MAAM,IAAI,KAAK,MAAM;;;;;;AAOnF,eAAe,SACd,IACA,cACA,aACA,QAC+B;AAC/B,KAAI;AACH,SAAO,MAAM,UAAU,IAAI,cAAc,aAAa,OAAO;UACrD,OAAO;AACf,MAAI,CAAC,oBAAoB,MAAM,CAAE,OAAM;;CAGxC,MAAM,yBAAS,IAAI,KAAqB;AACxC,MAAK,MAAM,cAAc,YACxB,KAAI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AAqB;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,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,8 +1,8 @@
|
|
|
1
|
-
import { c as __exportAll } from "./runner-
|
|
1
|
+
import { c as __exportAll } from "./runner-77GOZCnH.mjs";
|
|
2
2
|
import { t as validateIdentifier } from "./validate-BpwoDOgt.mjs";
|
|
3
3
|
import { p as invalidateTaxonomyObjectCache } from "./object-cache-71tPfV4A.mjs";
|
|
4
4
|
import { n as slugify } from "./slugify-B994zkXC.mjs";
|
|
5
|
-
import { t as withTransaction } from "./transaction-
|
|
5
|
+
import { t as withTransaction } from "./transaction-0KOpOyMu.mjs";
|
|
6
6
|
import { sql } from "kysely";
|
|
7
7
|
import { ulid } from "ulidx";
|
|
8
8
|
|
|
@@ -456,7 +456,7 @@ var TaxonomyRepository = class {
|
|
|
456
456
|
*/
|
|
457
457
|
async countEntriesForTerms(translationGroups) {
|
|
458
458
|
if (translationGroups.length === 0) return /* @__PURE__ */ new Map();
|
|
459
|
-
const { chunks, SQL_BATCH_SIZE } = await import("./chunks-
|
|
459
|
+
const { chunks, SQL_BATCH_SIZE } = await import("./chunks-bNiX6_DR.mjs").then((n) => n.r);
|
|
460
460
|
const counts = /* @__PURE__ */ new Map();
|
|
461
461
|
for (const chunk of chunks(translationGroups, SQL_BATCH_SIZE)) {
|
|
462
462
|
const rows = await this.db.selectFrom("content_taxonomies").select(["taxonomy_id", (eb) => eb.fn.count("entry_id").as("count")]).where("taxonomy_id", "in", chunk).groupBy("taxonomy_id").execute();
|
|
@@ -481,4 +481,4 @@ var TaxonomyRepository = class {
|
|
|
481
481
|
|
|
482
482
|
//#endregion
|
|
483
483
|
export { taxonomy_exports as n, TaxonomyRepository as t };
|
|
484
|
-
//# sourceMappingURL=taxonomy-
|
|
484
|
+
//# sourceMappingURL=taxonomy-8X09dLN5.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"taxonomy-BqCZ1TdU.mjs","names":[],"sources":["../src/database/repositories/taxonomy.ts"],"sourcesContent":["import { sql, type Kysely, type Selectable } from \"kysely\";\nimport { ulid } from \"ulidx\";\n\nimport { invalidateTaxonomyObjectCache } from \"../../object-cache/index.js\";\nimport { slugify } from \"../../utils/slugify.js\";\nimport { withTransaction } from \"../transaction.js\";\nimport type { Database, TaxonomyTable } from \"../types.js\";\nimport { validateIdentifier } from \"../validate.js\";\n\n/** A member of one sibling group and the position it currently holds. */\nexport interface SiblingPosition {\n\tgroup: string;\n\tposition: number;\n}\n\n/**\n * Translation groups per reorder `UPDATE`. Each costs three bound parameters —\n * a CASE `WHEN`/`THEN` pair plus one slot in the `IN` list — which keeps a\n * statement inside D1's 100-parameter ceiling.\n */\nconst GROUPS_PER_UPDATE = 32;\nconst NUMERIC_SUFFIX_PATTERN = /^\\d+$/;\n\n/** Deal the listed groups back out over the slots they hold, in the order given. */\nfunction permuteWithinSlots(\n\tlisted: readonly string[],\n\toccupied: readonly number[],\n): Map<string, number> {\n\tconst slots = occupied.toSorted((a, b) => a - b);\n\tconst target = new Map<string, number>();\n\tlisted.forEach((group, index) => {\n\t\tconst position = slots[index];\n\t\tif (position !== undefined) target.set(group, position);\n\t});\n\treturn target;\n}\n\n/**\n * Renumber a whole sibling group 0..n-1, with the listed groups in the order\n * given and every other member left in the place it already held.\n *\n * Works off each member's index in the sequence rather than its stored value,\n * which is what lets it resolve positions that tie. The sort is stable, so\n * tied members keep the order `siblings` arrives in — deterministic, but a\n * listing that mixes locales breaks a tie on whichever locale's label sorts\n * first, not on the order any one caller rendered.\n */\nfunction renumberSiblings(\n\tlisted: readonly string[],\n\tsiblings: readonly SiblingPosition[],\n): Map<string, number> {\n\tconst sequence = siblings.toSorted((a, b) => a.position - b.position);\n\tconst wanted = new Set(listed);\n\tconst target = new Map<string, number>();\n\tlet next = 0;\n\tsequence.forEach(({ group }, index) => {\n\t\tconst replacement = wanted.has(group) ? listed[next++] : undefined;\n\t\ttarget.set(replacement ?? group, index);\n\t});\n\treturn target;\n}\n\nexport interface Taxonomy {\n\tid: string;\n\tname: string;\n\tslug: string;\n\tlabel: string;\n\tparentId: string | null;\n\tdata: Record<string, unknown> | null;\n\tlocale: string;\n\ttranslationGroup: string | null;\n\t/**\n\t * Position among siblings. Shared by every row of a `translation_group` —\n\t * a term sits in the same place in every locale it is translated into.\n\t */\n\tsortOrder: number;\n}\n\nexport interface CreateTaxonomyInput {\n\tname: string;\n\tslug: string;\n\tlabel: string;\n\tparentId?: string;\n\tdata?: Record<string, unknown>;\n\t/** Omit to let the DB default (current value: 'en') apply. Higher layers\n\t * resolve the locale from the request context / i18n config. */\n\tlocale?: string;\n\t/** When set, links the new term into the source term's translation_group. */\n\ttranslationOf?: string;\n}\n\nexport interface UpdateTaxonomyInput {\n\tslug?: string;\n\tlabel?: string;\n\tparentId?: string | null;\n\tdata?: Record<string, unknown>;\n}\n\nexport interface FindOptions {\n\tparentId?: string | null;\n\tlocale?: string;\n}\n\nexport interface TaxonomyManualPageCursor {\n\tsortOrder: number;\n\tlabel: string;\n\tid: string;\n}\n\nexport interface TaxonomyPageOptions extends FindOptions {\n\tcursor?: TaxonomyManualPageCursor;\n\tlimit?: number;\n}\n\nexport interface TaxonomyPage {\n\titems: Taxonomy[];\n\thasMore: boolean;\n}\n\nexport interface TaxonomyAssignmentTranslation {\n\tid: string;\n\tslug: string;\n\tlocale: string;\n}\n\nexport interface TaxonomyAssignmentResolution {\n\ttranslationGroup: string;\n\tterm: Taxonomy | null;\n\tavailableLocales: string[];\n\ttranslations: TaxonomyAssignmentTranslation[];\n}\n\n/**\n * Taxonomy repository for categories, tags, and other classification.\n *\n * Terms are per-locale. Translations of the same term share a `translation_group`\n * ULID. `content_taxonomies` stores translation_groups on both sides so a single\n * association spans every locale of a post and term.\n *\n * Strict lookup methods use only the locale callers supply. The explicitly\n * resolved methods accept both the preferred and default locales so their\n * fallback policy stays visible at the call site.\n *\n * `sort_order` is per translation_group, not per row: every row sharing a\n * translation_group carries the same value, so a term holds one position across\n * all its locales. Sibling groups are keyed on the raw `parent_id` column, which\n * is locale-agnostic for the same reason (it stores the parent's\n * translation_group). Writes must preserve both invariants.\n */\nexport class TaxonomyRepository {\n\tconstructor(private db: Kysely<Database>) {}\n\n\t/**\n\t * Create a new taxonomy term. When `translationOf` is set the new row joins\n\t * the source term's translation_group; otherwise a fresh group is minted\n\t * (matching the migration backfill pattern `translation_group = id`).\n\t */\n\tasync create(input: CreateTaxonomyInput): Promise<Taxonomy> {\n\t\tconst id = ulid();\n\n\t\t// Empty-string parentId is coerced to null defensively. Higher layers\n\t\t// also normalize this — see handleTermCreate / handleTermUpdate.\n\t\t// `parent_id` stores the parent's locale-agnostic translation_group (not a\n\t\t// row id), mirroring content_taxonomies.taxonomy_id, so a child stays\n\t\t// nested in every locale's tree. resolveTranslationGroup accepts either a\n\t\t// row id or an already-resolved group, so this is idempotent.\n\t\tconst parentInput =\n\t\t\tinput.parentId === undefined || input.parentId === \"\" ? null : input.parentId;\n\t\tconst parentId = parentInput ? await this.resolveParentRef(parentInput) : null;\n\n\t\tlet translationGroup = id;\n\t\tlet sortOrder: number | null = null;\n\t\tif (input.translationOf) {\n\t\t\tconst source = await this.findById(input.translationOf);\n\t\t\tif (source?.translationGroup) translationGroup = source.translationGroup;\n\t\t\t// A translation is the same term in another locale, so it takes the\n\t\t\t// group's position — but only while it stays in the group that position\n\t\t\t// belongs to. Landing under a different parent makes it a new member of\n\t\t\t// that sibling group, and the source's position means nothing there.\n\t\t\tif (source && source.parentId === parentId) sortOrder = source.sortOrder;\n\t\t}\n\t\tsortOrder ??= await this.nextSortOrder(input.name, parentId);\n\n\t\tawait this.db\n\t\t\t.insertInto(\"taxonomies\")\n\t\t\t.values({\n\t\t\t\tid,\n\t\t\t\tname: input.name,\n\t\t\t\tslug: input.slug,\n\t\t\t\tlabel: input.label,\n\t\t\t\tparent_id: parentId,\n\t\t\t\tdata: input.data ? JSON.stringify(input.data) : null,\n\t\t\t\tsort_order: sortOrder,\n\t\t\t\t// When omitted, the DB DEFAULT 'en' is used — keeps behaviour\n\t\t\t\t// consistent with ContentRepository and lets higher layers\n\t\t\t\t// supply an explicit locale from request context.\n\t\t\t\t...(input.locale !== undefined ? { locale: input.locale } : {}),\n\t\t\t\ttranslation_group: translationGroup,\n\t\t\t})\n\t\t\t.execute();\n\n\t\tinvalidateTaxonomyObjectCache();\n\n\t\tconst taxonomy = await this.findById(id);\n\t\tif (!taxonomy) throw new Error(\"Failed to create taxonomy\");\n\t\treturn taxonomy;\n\t}\n\n\tasync findById(id: string): Promise<Taxonomy | null> {\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t.selectAll()\n\t\t\t.where(\"id\", \"=\", id)\n\t\t\t.executeTakeFirst();\n\t\treturn row ? this.rowToTaxonomy(row) : null;\n\t}\n\n\t/**\n\t * Find a term by (name, slug). When `locale` is provided, filter by it.\n\t * When omitted, returns the lowest-locale-code match (deterministic across\n\t * calls). Mirrors `ContentRepository.findBySlug`.\n\t */\n\tasync findBySlug(name: string, slug: string, locale?: string): Promise<Taxonomy | null> {\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t.selectAll()\n\t\t\t.where(\"name\", \"=\", name)\n\t\t\t.where(\"slug\", \"=\", slug);\n\t\tif (locale !== undefined) query = query.where(\"locale\", \"=\", locale);\n\t\tconst row = await query.orderBy(\"locale\", \"asc\").executeTakeFirst();\n\t\treturn row ? this.rowToTaxonomy(row) : null;\n\t}\n\n\t/** Generate a locale-scoped term slug, adding a numeric suffix when needed. */\n\tasync generateUniqueSlug(name: string, text: string, locale?: string): Promise<string> {\n\t\tconst baseSlug = slugify(text);\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t.select(\"slug\")\n\t\t\t.where(\"name\", \"=\", name)\n\t\t\t.where((eb) => eb.or([eb(\"slug\", \"=\", baseSlug), eb(\"slug\", \"like\", `${baseSlug}-%`)]));\n\t\tif (locale !== undefined) query = query.where(\"locale\", \"=\", locale);\n\t\tconst candidates = await query.execute();\n\t\tif (!candidates.some((candidate) => candidate.slug === baseSlug)) return baseSlug;\n\n\t\tlet maxSuffix = 0;\n\t\tconst prefix = `${baseSlug}-`;\n\t\tfor (const candidate of candidates) {\n\t\t\tif (!candidate.slug.startsWith(prefix)) continue;\n\t\t\tconst suffix = candidate.slug.slice(prefix.length);\n\t\t\tif (!NUMERIC_SUFFIX_PATTERN.test(suffix)) continue;\n\t\t\tmaxSuffix = Math.max(maxSuffix, Number.parseInt(suffix, 10));\n\t\t}\n\t\treturn `${baseSlug}-${maxSuffix + 1}`;\n\t}\n\n\t/**\n\t * Get all terms for a taxonomy (e.g., all categories).\n\t *\n\t * `sort_order` carries the manual order set from the admin; it is 0 for\n\t * terms nobody has reordered, so an untouched taxonomy still comes back\n\t * alphabetically. `id asc` is a stable tiebreaker for terms that share both\n\t * values. Without it the SQL ordering is implementation-defined when they match.\n\t */\n\tasync findByName(name: string, options: FindOptions = {}): Promise<Taxonomy[]> {\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t.selectAll()\n\t\t\t.where(\"name\", \"=\", name)\n\t\t\t.orderBy(\"sort_order\", \"asc\")\n\t\t\t.orderBy(\"label\", \"asc\")\n\t\t\t.orderBy(\"id\", \"asc\");\n\n\t\tif (options.locale !== undefined) query = query.where(\"locale\", \"=\", options.locale);\n\n\t\tif (options.parentId !== undefined) {\n\t\t\tif (options.parentId === null) {\n\t\t\t\tquery = query.where(\"parent_id\", \"is\", null);\n\t\t\t} else {\n\t\t\t\tquery = query.where(\"parent_id\", \"=\", options.parentId);\n\t\t\t}\n\t\t}\n\n\t\tconst rows = await query.execute();\n\t\treturn rows.map((row) => this.rowToTaxonomy(row));\n\t}\n\n\tasync findByNameResolved(\n\t\tname: string,\n\t\tlocale: string,\n\t\tdefaultLocale: string,\n\t): Promise<Taxonomy[]> {\n\t\tconst locales = [...new Set([locale, defaultLocale])];\n\t\tconst rows = await this.db\n\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t.selectAll()\n\t\t\t.where(\"name\", \"=\", name)\n\t\t\t.where(\"locale\", \"in\", locales)\n\t\t\t.orderBy(\"sort_order\", \"asc\")\n\t\t\t.orderBy(\"label\", \"asc\")\n\t\t\t.orderBy(\"id\", \"asc\")\n\t\t\t.execute();\n\n\t\tconst selected = new Map<string, Taxonomy>();\n\t\tfor (const row of rows) {\n\t\t\tconst term = this.rowToTaxonomy(row);\n\t\t\tconst group = term.translationGroup ?? term.id;\n\t\t\tconst current = selected.get(group);\n\t\t\tif (!current || term.locale === locale) selected.set(group, term);\n\t\t}\n\t\treturn [...selected.values()].toSorted(\n\t\t\t(a, b) =>\n\t\t\t\ta.sortOrder - b.sortOrder || a.label.localeCompare(b.label) || a.id.localeCompare(b.id),\n\t\t);\n\t}\n\n\tasync findPageByName(name: string, options: TaxonomyPageOptions = {}): Promise<TaxonomyPage> {\n\t\tconst limit = Math.max(1, Math.min(options.limit ?? 50, 100));\n\t\tlet query = this.db.selectFrom(\"taxonomies\").selectAll().where(\"name\", \"=\", name);\n\n\t\tif (options.locale !== undefined) query = query.where(\"locale\", \"=\", options.locale);\n\n\t\tif (options.parentId !== undefined) {\n\t\t\tquery =\n\t\t\t\toptions.parentId === null\n\t\t\t\t\t? query.where(\"parent_id\", \"is\", null)\n\t\t\t\t\t: query.where(\"parent_id\", \"=\", options.parentId);\n\t\t}\n\n\t\tif (options.cursor) {\n\t\t\tconst cursor = options.cursor;\n\t\t\tquery = query.where((eb) =>\n\t\t\t\teb.or([\n\t\t\t\t\teb(\"sort_order\", \">\", cursor.sortOrder),\n\t\t\t\t\teb.and([eb(\"sort_order\", \"=\", cursor.sortOrder), eb(\"label\", \">\", cursor.label)]),\n\t\t\t\t\teb.and([\n\t\t\t\t\t\teb(\"sort_order\", \"=\", cursor.sortOrder),\n\t\t\t\t\t\teb(\"label\", \"=\", cursor.label),\n\t\t\t\t\t\teb(\"id\", \">\", cursor.id),\n\t\t\t\t\t]),\n\t\t\t\t]),\n\t\t\t);\n\t\t}\n\t\tquery = query.orderBy(\"sort_order\", \"asc\").orderBy(\"label\", \"asc\").orderBy(\"id\", \"asc\");\n\n\t\tconst rows = await query.limit(limit + 1).execute();\n\t\treturn {\n\t\t\titems: rows.slice(0, limit).map((row) => this.rowToTaxonomy(row)),\n\t\t\thasMore: rows.length > limit,\n\t\t};\n\t}\n\n\t/**\n\t * Children of a term. Accepts a term id OR a translation_group and resolves\n\t * to the group, since `parent_id` stores the parent's translation_group.\n\t * Pass `locale` to scope to one locale's tree (children share the parent's\n\t * group across locales); omit it to find children in every locale (used to\n\t * block deletes that would orphan a sibling translation's subtree).\n\t */\n\tasync findChildren(parentIdOrGroup: string, locale?: string): Promise<Taxonomy[]> {\n\t\tconst group = await this.resolveTranslationGroup(parentIdOrGroup);\n\t\tif (!group) return [];\n\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t.selectAll()\n\t\t\t.where(\"parent_id\", \"=\", group)\n\t\t\t.orderBy(\"sort_order\", \"asc\")\n\t\t\t.orderBy(\"label\", \"asc\")\n\t\t\t.orderBy(\"id\", \"asc\");\n\t\tif (locale !== undefined) query = query.where(\"locale\", \"=\", locale);\n\n\t\tconst rows = await query.execute();\n\t\treturn rows.map((row) => this.rowToTaxonomy(row));\n\t}\n\n\t/**\n\t * Every translation sibling of a term (including itself), identified by\n\t * their shared `translation_group`.\n\t */\n\tasync findTranslations(translationGroup: string): Promise<Taxonomy[]> {\n\t\tconst rows = await this.db\n\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t.selectAll()\n\t\t\t.where(\"translation_group\", \"=\", translationGroup)\n\t\t\t.orderBy(\"locale\", \"asc\")\n\t\t\t.execute();\n\t\treturn rows.map((row) => this.rowToTaxonomy(row));\n\t}\n\n\tasync update(id: string, input: UpdateTaxonomyInput): Promise<Taxonomy | null> {\n\t\tconst existing = await this.findById(id);\n\t\tif (!existing) return null;\n\n\t\t// Per-row display fields. `parent_id` and `sort_order` are not here: both\n\t\t// belong to the translation_group and are written across it below.\n\t\tconst updates: Record<string, unknown> = {};\n\t\tif (input.slug !== undefined) updates.slug = input.slug;\n\t\tif (input.label !== undefined) updates.label = input.label;\n\t\tif (input.data !== undefined) updates.data = JSON.stringify(input.data);\n\n\t\tconst group: { parent_id?: string | null; sort_order?: number } = {};\n\t\tif (input.parentId !== undefined) {\n\t\t\t// Defense in depth: empty-string parentId means null (no parent).\n\t\t\t// Otherwise persist the parent's translation_group (locale-agnostic),\n\t\t\t// matching create() — see the note there.\n\t\t\tconst parentId =\n\t\t\t\tinput.parentId === \"\" || input.parentId === null\n\t\t\t\t\t? null\n\t\t\t\t\t: await this.resolveParentRef(input.parentId);\n\n\t\t\tif (parentId !== existing.parentId) {\n\t\t\t\tgroup.parent_id = parentId;\n\t\t\t\t// A position only means anything within one sibling group, so a term\n\t\t\t\t// that changes parent is appended to the group it lands in.\n\t\t\t\tgroup.sort_order = await this.nextSortOrder(existing.name, parentId);\n\t\t\t}\n\t\t}\n\n\t\tconst hasRowUpdates = Object.keys(updates).length > 0;\n\t\tconst hasGroupUpdates = Object.keys(group).length > 0;\n\t\tif (hasRowUpdates || hasGroupUpdates) {\n\t\t\tawait withTransaction(this.db, async (trx) => {\n\t\t\t\tif (hasRowUpdates) {\n\t\t\t\t\tawait trx.updateTable(\"taxonomies\").set(updates).where(\"id\", \"=\", id).execute();\n\t\t\t\t}\n\t\t\t\tif (hasGroupUpdates) {\n\t\t\t\t\tawait trx\n\t\t\t\t\t\t.updateTable(\"taxonomies\")\n\t\t\t\t\t\t.set(group)\n\t\t\t\t\t\t.where(\"translation_group\", \"=\", existing.translationGroup ?? existing.id)\n\t\t\t\t\t\t.execute();\n\t\t\t\t}\n\t\t\t});\n\t\t\tinvalidateTaxonomyObjectCache();\n\t\t}\n\n\t\treturn this.findById(id);\n\t}\n\n\t/**\n\t * Move `groups` (translation_groups, in the desired order) into the positions\n\t * those same groups already occupy, leaving every other member of the sibling\n\t * group where it is.\n\t *\n\t * `groups` may be a subset: a locale renders only the terms translated into\n\t * it, so an admin in `fr` often cannot name every member. A group left out\n\t * keeps its place, which is also what makes a stale list harmless.\n\t *\n\t * `siblings` is every member of the group with the position it holds, in a\n\t * listing's order — tied positions are resolved by that order, so pass it as\n\t * read. Groups already at their target are skipped, so one swap rewrites two\n\t * groups rather than the whole list.\n\t */\n\tasync reorder(groups: string[], siblings: readonly SiblingPosition[]): Promise<void> {\n\t\tconst current = new Map(siblings.map(({ group, position }) => [group, position]));\n\n\t\tconst listed: string[] = [];\n\t\tconst occupied: number[] = [];\n\t\tfor (const group of groups) {\n\t\t\tconst position = current.get(group);\n\t\t\tif (position === undefined) continue;\n\t\t\tlisted.push(group);\n\t\t\toccupied.push(position);\n\t\t}\n\t\tif (listed.length === 0) return;\n\n\t\t// Tied positions have no distinct order to permute into, so the requested\n\t\t// one would be dropped without a word. Renumbering is the only way to\n\t\t// honour it, and it repairs the tie on the way through.\n\t\tconst target =\n\t\t\tnew Set(occupied).size === occupied.length\n\t\t\t\t? permuteWithinSlots(listed, occupied)\n\t\t\t\t: renumberSiblings(listed, siblings);\n\n\t\tconst changed = [...target].filter(([group, position]) => current.get(group) !== position);\n\t\tif (changed.length === 0) return;\n\n\t\tawait this.applyPositions(changed);\n\n\t\tinvalidateTaxonomyObjectCache();\n\t}\n\n\t/**\n\t * Write one position per translation_group, GROUPS_PER_UPDATE at a time so\n\t * each statement stays inside D1's parameter ceiling.\n\t *\n\t * D1 has no transactions — `withTransaction` runs its callback bare there —\n\t * so a chunk is the unit that can't tear. A reorder spanning several chunks\n\t * can, and leaves ties, which the next reorder renumbers away.\n\t */\n\tprivate async applyPositions(positions: readonly (readonly [string, number])[]): Promise<void> {\n\t\tfor (let index = 0; index < positions.length; index += GROUPS_PER_UPDATE) {\n\t\t\tconst chunk = positions.slice(index, index + GROUPS_PER_UPDATE);\n\t\t\t// The CAST types the bound position. Postgres resolves a CASE whose THEN\n\t\t\t// arms are all untyped parameters to text, then refuses to assign text to\n\t\t\t// an integer column.\n\t\t\tconst arms = sql.join(\n\t\t\t\tchunk.map(([group, position]) => sql`WHEN ${group} THEN CAST(${position} AS INTEGER)`),\n\t\t\t\tsql` `,\n\t\t\t);\n\t\t\tconst keys = sql.join(chunk.map(([group]) => sql`${group}`));\n\t\t\tawait sql`\n\t\t\t\tUPDATE taxonomies\n\t\t\t\tSET sort_order = CASE translation_group ${arms} END\n\t\t\t\tWHERE translation_group IN (${keys})\n\t\t\t`.execute(this.db);\n\t\t}\n\t}\n\n\t/**\n\t * Position for a term joining a sibling group: one past the last member, or\n\t * 0 when the group is empty.\n\t *\n\t * Bounds are taken across every locale because a position belongs to the\n\t * translation_group, not to a row — a term translated into only one locale\n\t * still occupies its slot for all of them.\n\t */\n\tprivate async nextSortOrder(name: string, parentId: string | null): Promise<number> {\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t.select((eb) => eb.fn.max(\"sort_order\").as(\"max\"))\n\t\t\t.where(\"name\", \"=\", name);\n\t\tquery =\n\t\t\tparentId === null\n\t\t\t\t? query.where(\"parent_id\", \"is\", null)\n\t\t\t\t: query.where(\"parent_id\", \"=\", parentId);\n\n\t\tconst bounds = await query.executeTakeFirst();\n\t\t// Null only when the group is empty.\n\t\tif (!bounds || bounds.max === null) return 0;\n\t\treturn bounds.max + 1;\n\t}\n\n\tasync delete(id: string): Promise<boolean> {\n\t\tconst term = await this.findById(id);\n\t\tif (!term) return false;\n\n\t\t// When deleting the last translation of a group the pivot rows that\n\t\t// reference that translation_group become orphaned — purge them.\n\t\tif (term.translationGroup) {\n\t\t\tconst siblings = await this.db\n\t\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t\t.select(\"id\")\n\t\t\t\t.where(\"translation_group\", \"=\", term.translationGroup)\n\t\t\t\t.where(\"id\", \"!=\", id)\n\t\t\t\t.execute();\n\t\t\tif (siblings.length === 0) {\n\t\t\t\tawait this.db\n\t\t\t\t\t.deleteFrom(\"content_taxonomies\")\n\t\t\t\t\t.where(\"taxonomy_id\", \"=\", term.translationGroup)\n\t\t\t\t\t.execute();\n\t\t\t}\n\t\t}\n\n\t\tconst result = await this.db.deleteFrom(\"taxonomies\").where(\"id\", \"=\", id).executeTakeFirst();\n\t\tinvalidateTaxonomyObjectCache();\n\t\treturn (result.numDeletedRows ?? 0n) > 0n;\n\t}\n\n\t// --- Content-Taxonomy Junction (both ids store translation_groups) ---\n\n\tasync attachToEntry(collection: string, entryId: string, taxonomyId: string): Promise<void> {\n\t\tconst taxonomyGroup = await this.resolveTranslationGroup(taxonomyId);\n\t\tif (!taxonomyGroup) return;\n\t\tawait this.attachGroupsToEntry(collection, entryId, [taxonomyGroup]);\n\t}\n\n\t/**\n\t * Attach already-resolved term translation groups in one insert and return\n\t * the number of assignments that did not already exist.\n\t */\n\tasync attachGroupsToEntry(\n\t\tcollection: string,\n\t\tentryId: string,\n\t\ttaxonomyGroups: string[],\n\t): Promise<number> {\n\t\tconst uniqueGroups = [...new Set(taxonomyGroups)];\n\t\tif (uniqueGroups.length === 0) return 0;\n\t\tconst entryGroup = await this.resolveEntryTranslationGroup(collection, entryId);\n\t\tif (!entryGroup) return 0;\n\n\t\tconst result = await this.db\n\t\t\t.insertInto(\"content_taxonomies\")\n\t\t\t.values(\n\t\t\t\tuniqueGroups.map((taxonomy_id) => ({\n\t\t\t\t\tcollection,\n\t\t\t\t\tentry_id: entryGroup,\n\t\t\t\t\ttaxonomy_id,\n\t\t\t\t})),\n\t\t\t)\n\t\t\t.onConflict((oc) => oc.doNothing())\n\t\t\t.executeTakeFirst();\n\t\tconst inserted = Number(result.numInsertedOrUpdatedRows ?? 0n);\n\t\tif (inserted > 0) invalidateTaxonomyObjectCache();\n\t\treturn inserted;\n\t}\n\n\tasync detachFromEntry(collection: string, entryId: string, taxonomyId: string): Promise<void> {\n\t\tconst [entryGroup, taxonomyGroup] = await Promise.all([\n\t\t\tthis.resolveEntryTranslationGroup(collection, entryId),\n\t\t\tthis.resolveTranslationGroup(taxonomyId),\n\t\t]);\n\t\tif (!entryGroup || !taxonomyGroup) return;\n\n\t\tawait this.db\n\t\t\t.deleteFrom(\"content_taxonomies\")\n\t\t\t.where(\"collection\", \"=\", collection)\n\t\t\t.where(\"entry_id\", \"=\", entryGroup)\n\t\t\t.where(\"taxonomy_id\", \"=\", taxonomyGroup)\n\t\t\t.execute();\n\t\tinvalidateTaxonomyObjectCache();\n\t}\n\n\t/**\n\t * Taxonomy terms assigned to a content entry, resolved into a specific locale.\n\t * Terms whose translation_group lacks a row in the requested locale are\n\t * omitted — callers wanting fallback behaviour apply it themselves.\n\t */\n\tasync getTermsForEntry(\n\t\tcollection: string,\n\t\tentryId: string,\n\t\ttaxonomyName?: string,\n\t\tlocale?: string,\n\t): Promise<Taxonomy[]> {\n\t\tconst entryGroup = await this.resolveEntryTranslationGroup(collection, entryId);\n\t\tif (!entryGroup) return [];\n\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"content_taxonomies\")\n\t\t\t.innerJoin(\"taxonomies\", \"taxonomies.translation_group\", \"content_taxonomies.taxonomy_id\")\n\t\t\t.selectAll(\"taxonomies\")\n\t\t\t.where(\"content_taxonomies.collection\", \"=\", collection)\n\t\t\t.where(\"content_taxonomies.entry_id\", \"=\", entryGroup);\n\n\t\tif (taxonomyName) query = query.where(\"taxonomies.name\", \"=\", taxonomyName);\n\t\tif (locale !== undefined) query = query.where(\"taxonomies.locale\", \"=\", locale);\n\n\t\tconst rows = await query.orderBy(\"taxonomies.locale\", \"asc\").execute();\n\t\treturn rows.map((row) => this.rowToTaxonomy(row));\n\t}\n\n\tasync getTermAssignmentsForEntry(\n\t\tcollection: string,\n\t\tentryId: string,\n\t\ttaxonomyName: string,\n\t\tlocale: string,\n\t\tdefaultLocale: string,\n\t): Promise<TaxonomyAssignmentResolution[]> {\n\t\tconst entryGroup = await this.resolveEntryTranslationGroup(collection, entryId);\n\t\tif (!entryGroup) return [];\n\n\t\tconst rows = await this.db\n\t\t\t.selectFrom(\"content_taxonomies\")\n\t\t\t.innerJoin(\"taxonomies\", \"taxonomies.translation_group\", \"content_taxonomies.taxonomy_id\")\n\t\t\t.selectAll(\"taxonomies\")\n\t\t\t.select(\"content_taxonomies.taxonomy_id as assignment_group\")\n\t\t\t.where(\"content_taxonomies.collection\", \"=\", collection)\n\t\t\t.where(\"content_taxonomies.entry_id\", \"=\", entryGroup)\n\t\t\t.where(\"taxonomies.name\", \"=\", taxonomyName)\n\t\t\t.orderBy(\"content_taxonomies.taxonomy_id\", \"asc\")\n\t\t\t.orderBy(\"taxonomies.locale\", \"asc\")\n\t\t\t.execute();\n\n\t\tconst byGroup = new Map<string, Taxonomy[]>();\n\t\tfor (const row of rows) {\n\t\t\tconst variants = byGroup.get(row.assignment_group) ?? [];\n\t\t\tvariants.push(this.rowToTaxonomy(row));\n\t\t\tbyGroup.set(row.assignment_group, variants);\n\t\t}\n\n\t\treturn Array.from(byGroup, ([translationGroup, variants]) => {\n\t\t\tconst term =\n\t\t\t\tvariants.find((variant) => variant.locale === locale) ??\n\t\t\t\tvariants.find((variant) => variant.locale === defaultLocale) ??\n\t\t\t\tnull;\n\t\t\treturn {\n\t\t\t\ttranslationGroup,\n\t\t\t\tterm,\n\t\t\t\tavailableLocales: variants.map((variant) => variant.locale),\n\t\t\t\ttranslations: variants.map((variant) => ({\n\t\t\t\t\tid: variant.id,\n\t\t\t\t\tslug: variant.slug,\n\t\t\t\t\tlocale: variant.locale,\n\t\t\t\t})),\n\t\t\t};\n\t\t});\n\t}\n\n\t/**\n\t * Replace all assignments of a given taxonomy for one content entry.\n\t * Term ids OR translation_groups are accepted and normalised to groups.\n\t */\n\tasync setTermsForEntry(\n\t\tcollection: string,\n\t\tentryId: string,\n\t\ttaxonomyName: string,\n\t\ttermIds: string[],\n\t): Promise<void> {\n\t\tconst entryGroup = await this.resolveEntryTranslationGroup(collection, entryId);\n\t\tif (!entryGroup) return;\n\n\t\tconst groups: string[] = [];\n\t\tfor (const id of termIds) {\n\t\t\tconst group = await this.resolveTranslationGroup(id);\n\t\t\tif (group) groups.push(group);\n\t\t}\n\t\tconst newGroups = new Set(groups);\n\n\t\tconst current = await this.db\n\t\t\t.selectFrom(\"content_taxonomies\")\n\t\t\t.innerJoin(\"taxonomies\", \"taxonomies.translation_group\", \"content_taxonomies.taxonomy_id\")\n\t\t\t.select([\"content_taxonomies.taxonomy_id as group\"])\n\t\t\t.distinct()\n\t\t\t.where(\"content_taxonomies.collection\", \"=\", collection)\n\t\t\t.where(\"content_taxonomies.entry_id\", \"=\", entryGroup)\n\t\t\t.where(\"taxonomies.name\", \"=\", taxonomyName)\n\t\t\t.execute();\n\t\tconst currentGroups = new Set(current.map((r) => r.group));\n\n\t\tconst toRemove = [...currentGroups].filter((g) => !newGroups.has(g));\n\t\tif (toRemove.length > 0) {\n\t\t\tawait this.db\n\t\t\t\t.deleteFrom(\"content_taxonomies\")\n\t\t\t\t.where(\"collection\", \"=\", collection)\n\t\t\t\t.where(\"entry_id\", \"=\", entryGroup)\n\t\t\t\t.where(\"taxonomy_id\", \"in\", toRemove)\n\t\t\t\t.execute();\n\t\t}\n\n\t\tconst toAdd = [...newGroups].filter((g) => !currentGroups.has(g));\n\t\tif (toAdd.length > 0) {\n\t\t\tawait this.db\n\t\t\t\t.insertInto(\"content_taxonomies\")\n\t\t\t\t.values(\n\t\t\t\t\ttoAdd.map((taxonomy_id) => ({\n\t\t\t\t\t\tcollection,\n\t\t\t\t\t\tentry_id: entryGroup,\n\t\t\t\t\t\ttaxonomy_id,\n\t\t\t\t\t})),\n\t\t\t\t)\n\t\t\t\t.onConflict((oc) => oc.doNothing())\n\t\t\t\t.execute();\n\t\t}\n\n\t\tif (toRemove.length > 0 || toAdd.length > 0) invalidateTaxonomyObjectCache();\n\t}\n\n\tasync clearEntryTerms(collection: string, entryId: string): Promise<number> {\n\t\tconst entryGroup = await this.resolveEntryTranslationGroup(collection, entryId);\n\t\tif (!entryGroup) return 0;\n\n\t\tconst result = await this.db\n\t\t\t.deleteFrom(\"content_taxonomies\")\n\t\t\t.where(\"collection\", \"=\", collection)\n\t\t\t.where(\"entry_id\", \"=\", entryGroup)\n\t\t\t.executeTakeFirst();\n\t\tconst removed = Number(result.numDeletedRows ?? 0);\n\t\tif (removed > 0) invalidateTaxonomyObjectCache();\n\t\treturn removed;\n\t}\n\n\tprivate async resolveEntryTranslationGroup(\n\t\tcollection: string,\n\t\tentryIdOrGroup: string,\n\t): Promise<string | null> {\n\t\tvalidateIdentifier(collection, \"collection type\");\n\t\tconst tableName = `ec_${collection}`;\n\t\tconst result = await sql<{ translation_group: string }>`\n\t\t\tSELECT translation_group\n\t\t\tFROM ${sql.ref(tableName)}\n\t\t\tWHERE id = ${entryIdOrGroup} OR translation_group = ${entryIdOrGroup}\n\t\t\tLIMIT 1\n\t\t`.execute(this.db);\n\t\treturn result.rows[0]?.translation_group ?? null;\n\t}\n\n\t/**\n\t * Count content entries that use any translation of this term. Accepts\n\t * either a term id or a translation_group — we normalise to the group.\n\t *\n\t * Counts raw pivot rows regardless of the entry's status or deletion —\n\t * drafts and trashed entries are included. User-facing counts (admin term\n\t * list/get, public widget and term pages) use `fetchVisibleTermCounts`\n\t * from `taxonomies/term-counts.ts` instead, which counts only publicly\n\t * visible entries.\n\t */\n\tasync countEntriesWithTerm(termIdOrGroup: string): Promise<number> {\n\t\tconst group = await this.resolveTranslationGroup(termIdOrGroup);\n\t\tif (!group) return 0;\n\n\t\tconst result = await this.db\n\t\t\t.selectFrom(\"content_taxonomies\")\n\t\t\t.select((eb) => eb.fn.count(\"entry_id\").as(\"count\"))\n\t\t\t.where(\"taxonomy_id\", \"=\", group)\n\t\t\t.executeTakeFirst();\n\t\treturn Number(result?.count ?? 0);\n\t}\n\n\t/**\n\t * Resolve a parent reference (a row id or a translation_group) to the value\n\t * persisted in `parent_id`: the parent's translation_group, which is\n\t * locale-agnostic so the child stays nested in every locale. A\n\t * translation_group normally equals its anchor row's id, which satisfies the\n\t * self-FK on `parent_id`. If that anchor row is missing (a translation whose\n\t * anchor was deleted), fall back to the id we were given so we never write a\n\t * dangling FK value.\n\t */\n\tprivate async resolveParentRef(idOrGroup: string): Promise<string> {\n\t\tconst group = await this.resolveTranslationGroup(idOrGroup);\n\t\tif (!group) return idOrGroup;\n\t\tconst anchor = await this.db\n\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t.select(\"id\")\n\t\t\t.where(\"id\", \"=\", group)\n\t\t\t.executeTakeFirst();\n\t\treturn anchor ? group : idOrGroup;\n\t}\n\n\tprivate async resolveTranslationGroup(idOrGroup: string): Promise<string | null> {\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t.select([\"translation_group\"])\n\t\t\t.where((eb) => eb.or([eb(\"id\", \"=\", idOrGroup), eb(\"translation_group\", \"=\", idOrGroup)]))\n\t\t\t.executeTakeFirst();\n\t\treturn row?.translation_group ?? null;\n\t}\n\n\t/**\n\t * Batch count entries for multiple taxonomy translation_groups.\n\t * Chunks the query at SQL_BATCH_SIZE to stay below D1's bind-parameter limit.\n\t * Returns a Map from translation_group to count.\n\t *\n\t * Pass translation_groups (not term ids) — `content_taxonomies.taxonomy_id`\n\t * stores the translation_group so a single assignment spans every locale.\n\t *\n\t * Like `countEntriesWithTerm`, this counts raw pivot rows regardless of\n\t * status/deletion; user-facing counts go through `fetchVisibleTermCounts`.\n\t */\n\tasync countEntriesForTerms(translationGroups: string[]): Promise<Map<string, number>> {\n\t\tif (translationGroups.length === 0) return new Map();\n\n\t\tconst { chunks, SQL_BATCH_SIZE } = await import(\"../../utils/chunks.js\");\n\n\t\tconst counts = new Map<string, number>();\n\t\tfor (const chunk of chunks(translationGroups, SQL_BATCH_SIZE)) {\n\t\t\tconst rows = await this.db\n\t\t\t\t.selectFrom(\"content_taxonomies\")\n\t\t\t\t.select([\"taxonomy_id\", (eb) => eb.fn.count(\"entry_id\").as(\"count\")])\n\t\t\t\t.where(\"taxonomy_id\", \"in\", chunk)\n\t\t\t\t.groupBy(\"taxonomy_id\")\n\t\t\t\t.execute();\n\n\t\t\tfor (const row of rows) {\n\t\t\t\tcounts.set(row.taxonomy_id, Number(row.count || 0));\n\t\t\t}\n\t\t}\n\t\treturn counts;\n\t}\n\n\tprivate rowToTaxonomy(row: Selectable<TaxonomyTable>): Taxonomy {\n\t\treturn {\n\t\t\tid: row.id,\n\t\t\tname: row.name,\n\t\t\tslug: row.slug,\n\t\t\tlabel: row.label,\n\t\t\tparentId: row.parent_id,\n\t\t\tdata: row.data ? JSON.parse(row.data) : null,\n\t\t\tlocale: row.locale,\n\t\t\ttranslationGroup: row.translation_group,\n\t\t\tsortOrder: row.sort_order,\n\t\t};\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;AAoBA,MAAM,oBAAoB;AAC1B,MAAM,yBAAyB;;AAG/B,SAAS,mBACR,QACA,UACsB;CACtB,MAAM,QAAQ,SAAS,UAAU,GAAG,MAAM,IAAI,EAAE;CAChD,MAAM,yBAAS,IAAI,KAAqB;AACxC,QAAO,SAAS,OAAO,UAAU;EAChC,MAAM,WAAW,MAAM;AACvB,MAAI,aAAa,OAAW,QAAO,IAAI,OAAO,SAAS;GACtD;AACF,QAAO;;;;;;;;;;;;AAaR,SAAS,iBACR,QACA,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mB,MAAM,OAAO;EAEhD,MAAM,yBAAS,IAAI,KAAqB;AACxC,OAAK,MAAM,SAAS,OAAO,mBAAmB,eAAe,EAAE;GAC9D,MAAM,OAAO,MAAM,KAAK,GACtB,WAAW,qBAAqB,CAChC,OAAO,CAAC,gBAAgB,OAAO,GAAG,GAAG,MAAM,WAAW,CAAC,GAAG,QAAQ,CAAC,CAAC,CACpE,MAAM,eAAe,MAAM,MAAM,CACjC,QAAQ,cAAc,CACtB,SAAS;AAEX,QAAK,MAAM,OAAO,KACjB,QAAO,IAAI,IAAI,aAAa,OAAO,IAAI,SAAS,EAAE,CAAC;;AAGrD,SAAO;;CAGR,AAAQ,cAAc,KAA0C;AAC/D,SAAO;GACN,IAAI,IAAI;GACR,MAAM,IAAI;GACV,MAAM,IAAI;GACV,OAAO,IAAI;GACX,UAAU,IAAI;GACd,MAAM,IAAI,OAAO,KAAK,MAAM,IAAI,KAAK,GAAG;GACxC,QAAQ,IAAI;GACZ,kBAAkB,IAAI;GACtB,WAAW,IAAI;GACf"}
|
|
1
|
+
{"version":3,"file":"taxonomy-8X09dLN5.mjs","names":[],"sources":["../src/database/repositories/taxonomy.ts"],"sourcesContent":["import { sql, type Kysely, type Selectable } from \"kysely\";\nimport { ulid } from \"ulidx\";\n\nimport { invalidateTaxonomyObjectCache } from \"../../object-cache/index.js\";\nimport { slugify } from \"../../utils/slugify.js\";\nimport { withTransaction } from \"../transaction.js\";\nimport type { Database, TaxonomyTable } from \"../types.js\";\nimport { validateIdentifier } from \"../validate.js\";\n\n/** A member of one sibling group and the position it currently holds. */\nexport interface SiblingPosition {\n\tgroup: string;\n\tposition: number;\n}\n\n/**\n * Translation groups per reorder `UPDATE`. Each costs three bound parameters —\n * a CASE `WHEN`/`THEN` pair plus one slot in the `IN` list — which keeps a\n * statement inside D1's 100-parameter ceiling.\n */\nconst GROUPS_PER_UPDATE = 32;\nconst NUMERIC_SUFFIX_PATTERN = /^\\d+$/;\n\n/** Deal the listed groups back out over the slots they hold, in the order given. */\nfunction permuteWithinSlots(\n\tlisted: readonly string[],\n\toccupied: readonly number[],\n): Map<string, number> {\n\tconst slots = occupied.toSorted((a, b) => a - b);\n\tconst target = new Map<string, number>();\n\tlisted.forEach((group, index) => {\n\t\tconst position = slots[index];\n\t\tif (position !== undefined) target.set(group, position);\n\t});\n\treturn target;\n}\n\n/**\n * Renumber a whole sibling group 0..n-1, with the listed groups in the order\n * given and every other member left in the place it already held.\n *\n * Works off each member's index in the sequence rather than its stored value,\n * which is what lets it resolve positions that tie. The sort is stable, so\n * tied members keep the order `siblings` arrives in — deterministic, but a\n * listing that mixes locales breaks a tie on whichever locale's label sorts\n * first, not on the order any one caller rendered.\n */\nfunction renumberSiblings(\n\tlisted: readonly string[],\n\tsiblings: readonly SiblingPosition[],\n): Map<string, number> {\n\tconst sequence = siblings.toSorted((a, b) => a.position - b.position);\n\tconst wanted = new Set(listed);\n\tconst target = new Map<string, number>();\n\tlet next = 0;\n\tsequence.forEach(({ group }, index) => {\n\t\tconst replacement = wanted.has(group) ? listed[next++] : undefined;\n\t\ttarget.set(replacement ?? group, index);\n\t});\n\treturn target;\n}\n\nexport interface Taxonomy {\n\tid: string;\n\tname: string;\n\tslug: string;\n\tlabel: string;\n\tparentId: string | null;\n\tdata: Record<string, unknown> | null;\n\tlocale: string;\n\ttranslationGroup: string | null;\n\t/**\n\t * Position among siblings. Shared by every row of a `translation_group` —\n\t * a term sits in the same place in every locale it is translated into.\n\t */\n\tsortOrder: number;\n}\n\nexport interface CreateTaxonomyInput {\n\tname: string;\n\tslug: string;\n\tlabel: string;\n\tparentId?: string;\n\tdata?: Record<string, unknown>;\n\t/** Omit to let the DB default (current value: 'en') apply. Higher layers\n\t * resolve the locale from the request context / i18n config. */\n\tlocale?: string;\n\t/** When set, links the new term into the source term's translation_group. */\n\ttranslationOf?: string;\n}\n\nexport interface UpdateTaxonomyInput {\n\tslug?: string;\n\tlabel?: string;\n\tparentId?: string | null;\n\tdata?: Record<string, unknown>;\n}\n\nexport interface FindOptions {\n\tparentId?: string | null;\n\tlocale?: string;\n}\n\nexport interface TaxonomyManualPageCursor {\n\tsortOrder: number;\n\tlabel: string;\n\tid: string;\n}\n\nexport interface TaxonomyPageOptions extends FindOptions {\n\tcursor?: TaxonomyManualPageCursor;\n\tlimit?: number;\n}\n\nexport interface TaxonomyPage {\n\titems: Taxonomy[];\n\thasMore: boolean;\n}\n\nexport interface TaxonomyAssignmentTranslation {\n\tid: string;\n\tslug: string;\n\tlocale: string;\n}\n\nexport interface TaxonomyAssignmentResolution {\n\ttranslationGroup: string;\n\tterm: Taxonomy | null;\n\tavailableLocales: string[];\n\ttranslations: TaxonomyAssignmentTranslation[];\n}\n\n/**\n * Taxonomy repository for categories, tags, and other classification.\n *\n * Terms are per-locale. Translations of the same term share a `translation_group`\n * ULID. `content_taxonomies` stores translation_groups on both sides so a single\n * association spans every locale of a post and term.\n *\n * Strict lookup methods use only the locale callers supply. The explicitly\n * resolved methods accept both the preferred and default locales so their\n * fallback policy stays visible at the call site.\n *\n * `sort_order` is per translation_group, not per row: every row sharing a\n * translation_group carries the same value, so a term holds one position across\n * all its locales. Sibling groups are keyed on the raw `parent_id` column, which\n * is locale-agnostic for the same reason (it stores the parent's\n * translation_group). Writes must preserve both invariants.\n */\nexport class TaxonomyRepository {\n\tconstructor(private db: Kysely<Database>) {}\n\n\t/**\n\t * Create a new taxonomy term. When `translationOf` is set the new row joins\n\t * the source term's translation_group; otherwise a fresh group is minted\n\t * (matching the migration backfill pattern `translation_group = id`).\n\t */\n\tasync create(input: CreateTaxonomyInput): Promise<Taxonomy> {\n\t\tconst id = ulid();\n\n\t\t// Empty-string parentId is coerced to null defensively. Higher layers\n\t\t// also normalize this — see handleTermCreate / handleTermUpdate.\n\t\t// `parent_id` stores the parent's locale-agnostic translation_group (not a\n\t\t// row id), mirroring content_taxonomies.taxonomy_id, so a child stays\n\t\t// nested in every locale's tree. resolveTranslationGroup accepts either a\n\t\t// row id or an already-resolved group, so this is idempotent.\n\t\tconst parentInput =\n\t\t\tinput.parentId === undefined || input.parentId === \"\" ? null : input.parentId;\n\t\tconst parentId = parentInput ? await this.resolveParentRef(parentInput) : null;\n\n\t\tlet translationGroup = id;\n\t\tlet sortOrder: number | null = null;\n\t\tif (input.translationOf) {\n\t\t\tconst source = await this.findById(input.translationOf);\n\t\t\tif (source?.translationGroup) translationGroup = source.translationGroup;\n\t\t\t// A translation is the same term in another locale, so it takes the\n\t\t\t// group's position — but only while it stays in the group that position\n\t\t\t// belongs to. Landing under a different parent makes it a new member of\n\t\t\t// that sibling group, and the source's position means nothing there.\n\t\t\tif (source && source.parentId === parentId) sortOrder = source.sortOrder;\n\t\t}\n\t\tsortOrder ??= await this.nextSortOrder(input.name, parentId);\n\n\t\tawait this.db\n\t\t\t.insertInto(\"taxonomies\")\n\t\t\t.values({\n\t\t\t\tid,\n\t\t\t\tname: input.name,\n\t\t\t\tslug: input.slug,\n\t\t\t\tlabel: input.label,\n\t\t\t\tparent_id: parentId,\n\t\t\t\tdata: input.data ? JSON.stringify(input.data) : null,\n\t\t\t\tsort_order: sortOrder,\n\t\t\t\t// When omitted, the DB DEFAULT 'en' is used — keeps behaviour\n\t\t\t\t// consistent with ContentRepository and lets higher layers\n\t\t\t\t// supply an explicit locale from request context.\n\t\t\t\t...(input.locale !== undefined ? { locale: input.locale } : {}),\n\t\t\t\ttranslation_group: translationGroup,\n\t\t\t})\n\t\t\t.execute();\n\n\t\tinvalidateTaxonomyObjectCache();\n\n\t\tconst taxonomy = await this.findById(id);\n\t\tif (!taxonomy) throw new Error(\"Failed to create taxonomy\");\n\t\treturn taxonomy;\n\t}\n\n\tasync findById(id: string): Promise<Taxonomy | null> {\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t.selectAll()\n\t\t\t.where(\"id\", \"=\", id)\n\t\t\t.executeTakeFirst();\n\t\treturn row ? this.rowToTaxonomy(row) : null;\n\t}\n\n\t/**\n\t * Find a term by (name, slug). When `locale` is provided, filter by it.\n\t * When omitted, returns the lowest-locale-code match (deterministic across\n\t * calls). Mirrors `ContentRepository.findBySlug`.\n\t */\n\tasync findBySlug(name: string, slug: string, locale?: string): Promise<Taxonomy | null> {\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t.selectAll()\n\t\t\t.where(\"name\", \"=\", name)\n\t\t\t.where(\"slug\", \"=\", slug);\n\t\tif (locale !== undefined) query = query.where(\"locale\", \"=\", locale);\n\t\tconst row = await query.orderBy(\"locale\", \"asc\").executeTakeFirst();\n\t\treturn row ? this.rowToTaxonomy(row) : null;\n\t}\n\n\t/** Generate a locale-scoped term slug, adding a numeric suffix when needed. */\n\tasync generateUniqueSlug(name: string, text: string, locale?: string): Promise<string> {\n\t\tconst baseSlug = slugify(text);\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t.select(\"slug\")\n\t\t\t.where(\"name\", \"=\", name)\n\t\t\t.where((eb) => eb.or([eb(\"slug\", \"=\", baseSlug), eb(\"slug\", \"like\", `${baseSlug}-%`)]));\n\t\tif (locale !== undefined) query = query.where(\"locale\", \"=\", locale);\n\t\tconst candidates = await query.execute();\n\t\tif (!candidates.some((candidate) => candidate.slug === baseSlug)) return baseSlug;\n\n\t\tlet maxSuffix = 0;\n\t\tconst prefix = `${baseSlug}-`;\n\t\tfor (const candidate of candidates) {\n\t\t\tif (!candidate.slug.startsWith(prefix)) continue;\n\t\t\tconst suffix = candidate.slug.slice(prefix.length);\n\t\t\tif (!NUMERIC_SUFFIX_PATTERN.test(suffix)) continue;\n\t\t\tmaxSuffix = Math.max(maxSuffix, Number.parseInt(suffix, 10));\n\t\t}\n\t\treturn `${baseSlug}-${maxSuffix + 1}`;\n\t}\n\n\t/**\n\t * Get all terms for a taxonomy (e.g., all categories).\n\t *\n\t * `sort_order` carries the manual order set from the admin; it is 0 for\n\t * terms nobody has reordered, so an untouched taxonomy still comes back\n\t * alphabetically. `id asc` is a stable tiebreaker for terms that share both\n\t * values. Without it the SQL ordering is implementation-defined when they match.\n\t */\n\tasync findByName(name: string, options: FindOptions = {}): Promise<Taxonomy[]> {\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t.selectAll()\n\t\t\t.where(\"name\", \"=\", name)\n\t\t\t.orderBy(\"sort_order\", \"asc\")\n\t\t\t.orderBy(\"label\", \"asc\")\n\t\t\t.orderBy(\"id\", \"asc\");\n\n\t\tif (options.locale !== undefined) query = query.where(\"locale\", \"=\", options.locale);\n\n\t\tif (options.parentId !== undefined) {\n\t\t\tif (options.parentId === null) {\n\t\t\t\tquery = query.where(\"parent_id\", \"is\", null);\n\t\t\t} else {\n\t\t\t\tquery = query.where(\"parent_id\", \"=\", options.parentId);\n\t\t\t}\n\t\t}\n\n\t\tconst rows = await query.execute();\n\t\treturn rows.map((row) => this.rowToTaxonomy(row));\n\t}\n\n\tasync findByNameResolved(\n\t\tname: string,\n\t\tlocale: string,\n\t\tdefaultLocale: string,\n\t): Promise<Taxonomy[]> {\n\t\tconst locales = [...new Set([locale, defaultLocale])];\n\t\tconst rows = await this.db\n\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t.selectAll()\n\t\t\t.where(\"name\", \"=\", name)\n\t\t\t.where(\"locale\", \"in\", locales)\n\t\t\t.orderBy(\"sort_order\", \"asc\")\n\t\t\t.orderBy(\"label\", \"asc\")\n\t\t\t.orderBy(\"id\", \"asc\")\n\t\t\t.execute();\n\n\t\tconst selected = new Map<string, Taxonomy>();\n\t\tfor (const row of rows) {\n\t\t\tconst term = this.rowToTaxonomy(row);\n\t\t\tconst group = term.translationGroup ?? term.id;\n\t\t\tconst current = selected.get(group);\n\t\t\tif (!current || term.locale === locale) selected.set(group, term);\n\t\t}\n\t\treturn [...selected.values()].toSorted(\n\t\t\t(a, b) =>\n\t\t\t\ta.sortOrder - b.sortOrder || a.label.localeCompare(b.label) || a.id.localeCompare(b.id),\n\t\t);\n\t}\n\n\tasync findPageByName(name: string, options: TaxonomyPageOptions = {}): Promise<TaxonomyPage> {\n\t\tconst limit = Math.max(1, Math.min(options.limit ?? 50, 100));\n\t\tlet query = this.db.selectFrom(\"taxonomies\").selectAll().where(\"name\", \"=\", name);\n\n\t\tif (options.locale !== undefined) query = query.where(\"locale\", \"=\", options.locale);\n\n\t\tif (options.parentId !== undefined) {\n\t\t\tquery =\n\t\t\t\toptions.parentId === null\n\t\t\t\t\t? query.where(\"parent_id\", \"is\", null)\n\t\t\t\t\t: query.where(\"parent_id\", \"=\", options.parentId);\n\t\t}\n\n\t\tif (options.cursor) {\n\t\t\tconst cursor = options.cursor;\n\t\t\tquery = query.where((eb) =>\n\t\t\t\teb.or([\n\t\t\t\t\teb(\"sort_order\", \">\", cursor.sortOrder),\n\t\t\t\t\teb.and([eb(\"sort_order\", \"=\", cursor.sortOrder), eb(\"label\", \">\", cursor.label)]),\n\t\t\t\t\teb.and([\n\t\t\t\t\t\teb(\"sort_order\", \"=\", cursor.sortOrder),\n\t\t\t\t\t\teb(\"label\", \"=\", cursor.label),\n\t\t\t\t\t\teb(\"id\", \">\", cursor.id),\n\t\t\t\t\t]),\n\t\t\t\t]),\n\t\t\t);\n\t\t}\n\t\tquery = query.orderBy(\"sort_order\", \"asc\").orderBy(\"label\", \"asc\").orderBy(\"id\", \"asc\");\n\n\t\tconst rows = await query.limit(limit + 1).execute();\n\t\treturn {\n\t\t\titems: rows.slice(0, limit).map((row) => this.rowToTaxonomy(row)),\n\t\t\thasMore: rows.length > limit,\n\t\t};\n\t}\n\n\t/**\n\t * Children of a term. Accepts a term id OR a translation_group and resolves\n\t * to the group, since `parent_id` stores the parent's translation_group.\n\t * Pass `locale` to scope to one locale's tree (children share the parent's\n\t * group across locales); omit it to find children in every locale (used to\n\t * block deletes that would orphan a sibling translation's subtree).\n\t */\n\tasync findChildren(parentIdOrGroup: string, locale?: string): Promise<Taxonomy[]> {\n\t\tconst group = await this.resolveTranslationGroup(parentIdOrGroup);\n\t\tif (!group) return [];\n\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t.selectAll()\n\t\t\t.where(\"parent_id\", \"=\", group)\n\t\t\t.orderBy(\"sort_order\", \"asc\")\n\t\t\t.orderBy(\"label\", \"asc\")\n\t\t\t.orderBy(\"id\", \"asc\");\n\t\tif (locale !== undefined) query = query.where(\"locale\", \"=\", locale);\n\n\t\tconst rows = await query.execute();\n\t\treturn rows.map((row) => this.rowToTaxonomy(row));\n\t}\n\n\t/**\n\t * Every translation sibling of a term (including itself), identified by\n\t * their shared `translation_group`.\n\t */\n\tasync findTranslations(translationGroup: string): Promise<Taxonomy[]> {\n\t\tconst rows = await this.db\n\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t.selectAll()\n\t\t\t.where(\"translation_group\", \"=\", translationGroup)\n\t\t\t.orderBy(\"locale\", \"asc\")\n\t\t\t.execute();\n\t\treturn rows.map((row) => this.rowToTaxonomy(row));\n\t}\n\n\tasync update(id: string, input: UpdateTaxonomyInput): Promise<Taxonomy | null> {\n\t\tconst existing = await this.findById(id);\n\t\tif (!existing) return null;\n\n\t\t// Per-row display fields. `parent_id` and `sort_order` are not here: both\n\t\t// belong to the translation_group and are written across it below.\n\t\tconst updates: Record<string, unknown> = {};\n\t\tif (input.slug !== undefined) updates.slug = input.slug;\n\t\tif (input.label !== undefined) updates.label = input.label;\n\t\tif (input.data !== undefined) updates.data = JSON.stringify(input.data);\n\n\t\tconst group: { parent_id?: string | null; sort_order?: number } = {};\n\t\tif (input.parentId !== undefined) {\n\t\t\t// Defense in depth: empty-string parentId means null (no parent).\n\t\t\t// Otherwise persist the parent's translation_group (locale-agnostic),\n\t\t\t// matching create() — see the note there.\n\t\t\tconst parentId =\n\t\t\t\tinput.parentId === \"\" || input.parentId === null\n\t\t\t\t\t? null\n\t\t\t\t\t: await this.resolveParentRef(input.parentId);\n\n\t\t\tif (parentId !== existing.parentId) {\n\t\t\t\tgroup.parent_id = parentId;\n\t\t\t\t// A position only means anything within one sibling group, so a term\n\t\t\t\t// that changes parent is appended to the group it lands in.\n\t\t\t\tgroup.sort_order = await this.nextSortOrder(existing.name, parentId);\n\t\t\t}\n\t\t}\n\n\t\tconst hasRowUpdates = Object.keys(updates).length > 0;\n\t\tconst hasGroupUpdates = Object.keys(group).length > 0;\n\t\tif (hasRowUpdates || hasGroupUpdates) {\n\t\t\tawait withTransaction(this.db, async (trx) => {\n\t\t\t\tif (hasRowUpdates) {\n\t\t\t\t\tawait trx.updateTable(\"taxonomies\").set(updates).where(\"id\", \"=\", id).execute();\n\t\t\t\t}\n\t\t\t\tif (hasGroupUpdates) {\n\t\t\t\t\tawait trx\n\t\t\t\t\t\t.updateTable(\"taxonomies\")\n\t\t\t\t\t\t.set(group)\n\t\t\t\t\t\t.where(\"translation_group\", \"=\", existing.translationGroup ?? existing.id)\n\t\t\t\t\t\t.execute();\n\t\t\t\t}\n\t\t\t});\n\t\t\tinvalidateTaxonomyObjectCache();\n\t\t}\n\n\t\treturn this.findById(id);\n\t}\n\n\t/**\n\t * Move `groups` (translation_groups, in the desired order) into the positions\n\t * those same groups already occupy, leaving every other member of the sibling\n\t * group where it is.\n\t *\n\t * `groups` may be a subset: a locale renders only the terms translated into\n\t * it, so an admin in `fr` often cannot name every member. A group left out\n\t * keeps its place, which is also what makes a stale list harmless.\n\t *\n\t * `siblings` is every member of the group with the position it holds, in a\n\t * listing's order — tied positions are resolved by that order, so pass it as\n\t * read. Groups already at their target are skipped, so one swap rewrites two\n\t * groups rather than the whole list.\n\t */\n\tasync reorder(groups: string[], siblings: readonly SiblingPosition[]): Promise<void> {\n\t\tconst current = new Map(siblings.map(({ group, position }) => [group, position]));\n\n\t\tconst listed: string[] = [];\n\t\tconst occupied: number[] = [];\n\t\tfor (const group of groups) {\n\t\t\tconst position = current.get(group);\n\t\t\tif (position === undefined) continue;\n\t\t\tlisted.push(group);\n\t\t\toccupied.push(position);\n\t\t}\n\t\tif (listed.length === 0) return;\n\n\t\t// Tied positions have no distinct order to permute into, so the requested\n\t\t// one would be dropped without a word. Renumbering is the only way to\n\t\t// honour it, and it repairs the tie on the way through.\n\t\tconst target =\n\t\t\tnew Set(occupied).size === occupied.length\n\t\t\t\t? permuteWithinSlots(listed, occupied)\n\t\t\t\t: renumberSiblings(listed, siblings);\n\n\t\tconst changed = [...target].filter(([group, position]) => current.get(group) !== position);\n\t\tif (changed.length === 0) return;\n\n\t\tawait this.applyPositions(changed);\n\n\t\tinvalidateTaxonomyObjectCache();\n\t}\n\n\t/**\n\t * Write one position per translation_group, GROUPS_PER_UPDATE at a time so\n\t * each statement stays inside D1's parameter ceiling.\n\t *\n\t * D1 has no transactions — `withTransaction` runs its callback bare there —\n\t * so a chunk is the unit that can't tear. A reorder spanning several chunks\n\t * can, and leaves ties, which the next reorder renumbers away.\n\t */\n\tprivate async applyPositions(positions: readonly (readonly [string, number])[]): Promise<void> {\n\t\tfor (let index = 0; index < positions.length; index += GROUPS_PER_UPDATE) {\n\t\t\tconst chunk = positions.slice(index, index + GROUPS_PER_UPDATE);\n\t\t\t// The CAST types the bound position. Postgres resolves a CASE whose THEN\n\t\t\t// arms are all untyped parameters to text, then refuses to assign text to\n\t\t\t// an integer column.\n\t\t\tconst arms = sql.join(\n\t\t\t\tchunk.map(([group, position]) => sql`WHEN ${group} THEN CAST(${position} AS INTEGER)`),\n\t\t\t\tsql` `,\n\t\t\t);\n\t\t\tconst keys = sql.join(chunk.map(([group]) => sql`${group}`));\n\t\t\tawait sql`\n\t\t\t\tUPDATE taxonomies\n\t\t\t\tSET sort_order = CASE translation_group ${arms} END\n\t\t\t\tWHERE translation_group IN (${keys})\n\t\t\t`.execute(this.db);\n\t\t}\n\t}\n\n\t/**\n\t * Position for a term joining a sibling group: one past the last member, or\n\t * 0 when the group is empty.\n\t *\n\t * Bounds are taken across every locale because a position belongs to the\n\t * translation_group, not to a row — a term translated into only one locale\n\t * still occupies its slot for all of them.\n\t */\n\tprivate async nextSortOrder(name: string, parentId: string | null): Promise<number> {\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t.select((eb) => eb.fn.max(\"sort_order\").as(\"max\"))\n\t\t\t.where(\"name\", \"=\", name);\n\t\tquery =\n\t\t\tparentId === null\n\t\t\t\t? query.where(\"parent_id\", \"is\", null)\n\t\t\t\t: query.where(\"parent_id\", \"=\", parentId);\n\n\t\tconst bounds = await query.executeTakeFirst();\n\t\t// Null only when the group is empty.\n\t\tif (!bounds || bounds.max === null) return 0;\n\t\treturn bounds.max + 1;\n\t}\n\n\tasync delete(id: string): Promise<boolean> {\n\t\tconst term = await this.findById(id);\n\t\tif (!term) return false;\n\n\t\t// When deleting the last translation of a group the pivot rows that\n\t\t// reference that translation_group become orphaned — purge them.\n\t\tif (term.translationGroup) {\n\t\t\tconst siblings = await this.db\n\t\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t\t.select(\"id\")\n\t\t\t\t.where(\"translation_group\", \"=\", term.translationGroup)\n\t\t\t\t.where(\"id\", \"!=\", id)\n\t\t\t\t.execute();\n\t\t\tif (siblings.length === 0) {\n\t\t\t\tawait this.db\n\t\t\t\t\t.deleteFrom(\"content_taxonomies\")\n\t\t\t\t\t.where(\"taxonomy_id\", \"=\", term.translationGroup)\n\t\t\t\t\t.execute();\n\t\t\t}\n\t\t}\n\n\t\tconst result = await this.db.deleteFrom(\"taxonomies\").where(\"id\", \"=\", id).executeTakeFirst();\n\t\tinvalidateTaxonomyObjectCache();\n\t\treturn (result.numDeletedRows ?? 0n) > 0n;\n\t}\n\n\t// --- Content-Taxonomy Junction (both ids store translation_groups) ---\n\n\tasync attachToEntry(collection: string, entryId: string, taxonomyId: string): Promise<void> {\n\t\tconst taxonomyGroup = await this.resolveTranslationGroup(taxonomyId);\n\t\tif (!taxonomyGroup) return;\n\t\tawait this.attachGroupsToEntry(collection, entryId, [taxonomyGroup]);\n\t}\n\n\t/**\n\t * Attach already-resolved term translation groups in one insert and return\n\t * the number of assignments that did not already exist.\n\t */\n\tasync attachGroupsToEntry(\n\t\tcollection: string,\n\t\tentryId: string,\n\t\ttaxonomyGroups: string[],\n\t): Promise<number> {\n\t\tconst uniqueGroups = [...new Set(taxonomyGroups)];\n\t\tif (uniqueGroups.length === 0) return 0;\n\t\tconst entryGroup = await this.resolveEntryTranslationGroup(collection, entryId);\n\t\tif (!entryGroup) return 0;\n\n\t\tconst result = await this.db\n\t\t\t.insertInto(\"content_taxonomies\")\n\t\t\t.values(\n\t\t\t\tuniqueGroups.map((taxonomy_id) => ({\n\t\t\t\t\tcollection,\n\t\t\t\t\tentry_id: entryGroup,\n\t\t\t\t\ttaxonomy_id,\n\t\t\t\t})),\n\t\t\t)\n\t\t\t.onConflict((oc) => oc.doNothing())\n\t\t\t.executeTakeFirst();\n\t\tconst inserted = Number(result.numInsertedOrUpdatedRows ?? 0n);\n\t\tif (inserted > 0) invalidateTaxonomyObjectCache();\n\t\treturn inserted;\n\t}\n\n\tasync detachFromEntry(collection: string, entryId: string, taxonomyId: string): Promise<void> {\n\t\tconst [entryGroup, taxonomyGroup] = await Promise.all([\n\t\t\tthis.resolveEntryTranslationGroup(collection, entryId),\n\t\t\tthis.resolveTranslationGroup(taxonomyId),\n\t\t]);\n\t\tif (!entryGroup || !taxonomyGroup) return;\n\n\t\tawait this.db\n\t\t\t.deleteFrom(\"content_taxonomies\")\n\t\t\t.where(\"collection\", \"=\", collection)\n\t\t\t.where(\"entry_id\", \"=\", entryGroup)\n\t\t\t.where(\"taxonomy_id\", \"=\", taxonomyGroup)\n\t\t\t.execute();\n\t\tinvalidateTaxonomyObjectCache();\n\t}\n\n\t/**\n\t * Taxonomy terms assigned to a content entry, resolved into a specific locale.\n\t * Terms whose translation_group lacks a row in the requested locale are\n\t * omitted — callers wanting fallback behaviour apply it themselves.\n\t */\n\tasync getTermsForEntry(\n\t\tcollection: string,\n\t\tentryId: string,\n\t\ttaxonomyName?: string,\n\t\tlocale?: string,\n\t): Promise<Taxonomy[]> {\n\t\tconst entryGroup = await this.resolveEntryTranslationGroup(collection, entryId);\n\t\tif (!entryGroup) return [];\n\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"content_taxonomies\")\n\t\t\t.innerJoin(\"taxonomies\", \"taxonomies.translation_group\", \"content_taxonomies.taxonomy_id\")\n\t\t\t.selectAll(\"taxonomies\")\n\t\t\t.where(\"content_taxonomies.collection\", \"=\", collection)\n\t\t\t.where(\"content_taxonomies.entry_id\", \"=\", entryGroup);\n\n\t\tif (taxonomyName) query = query.where(\"taxonomies.name\", \"=\", taxonomyName);\n\t\tif (locale !== undefined) query = query.where(\"taxonomies.locale\", \"=\", locale);\n\n\t\tconst rows = await query.orderBy(\"taxonomies.locale\", \"asc\").execute();\n\t\treturn rows.map((row) => this.rowToTaxonomy(row));\n\t}\n\n\tasync getTermAssignmentsForEntry(\n\t\tcollection: string,\n\t\tentryId: string,\n\t\ttaxonomyName: string,\n\t\tlocale: string,\n\t\tdefaultLocale: string,\n\t): Promise<TaxonomyAssignmentResolution[]> {\n\t\tconst entryGroup = await this.resolveEntryTranslationGroup(collection, entryId);\n\t\tif (!entryGroup) return [];\n\n\t\tconst rows = await this.db\n\t\t\t.selectFrom(\"content_taxonomies\")\n\t\t\t.innerJoin(\"taxonomies\", \"taxonomies.translation_group\", \"content_taxonomies.taxonomy_id\")\n\t\t\t.selectAll(\"taxonomies\")\n\t\t\t.select(\"content_taxonomies.taxonomy_id as assignment_group\")\n\t\t\t.where(\"content_taxonomies.collection\", \"=\", collection)\n\t\t\t.where(\"content_taxonomies.entry_id\", \"=\", entryGroup)\n\t\t\t.where(\"taxonomies.name\", \"=\", taxonomyName)\n\t\t\t.orderBy(\"content_taxonomies.taxonomy_id\", \"asc\")\n\t\t\t.orderBy(\"taxonomies.locale\", \"asc\")\n\t\t\t.execute();\n\n\t\tconst byGroup = new Map<string, Taxonomy[]>();\n\t\tfor (const row of rows) {\n\t\t\tconst variants = byGroup.get(row.assignment_group) ?? [];\n\t\t\tvariants.push(this.rowToTaxonomy(row));\n\t\t\tbyGroup.set(row.assignment_group, variants);\n\t\t}\n\n\t\treturn Array.from(byGroup, ([translationGroup, variants]) => {\n\t\t\tconst term =\n\t\t\t\tvariants.find((variant) => variant.locale === locale) ??\n\t\t\t\tvariants.find((variant) => variant.locale === defaultLocale) ??\n\t\t\t\tnull;\n\t\t\treturn {\n\t\t\t\ttranslationGroup,\n\t\t\t\tterm,\n\t\t\t\tavailableLocales: variants.map((variant) => variant.locale),\n\t\t\t\ttranslations: variants.map((variant) => ({\n\t\t\t\t\tid: variant.id,\n\t\t\t\t\tslug: variant.slug,\n\t\t\t\t\tlocale: variant.locale,\n\t\t\t\t})),\n\t\t\t};\n\t\t});\n\t}\n\n\t/**\n\t * Replace all assignments of a given taxonomy for one content entry.\n\t * Term ids OR translation_groups are accepted and normalised to groups.\n\t */\n\tasync setTermsForEntry(\n\t\tcollection: string,\n\t\tentryId: string,\n\t\ttaxonomyName: string,\n\t\ttermIds: string[],\n\t): Promise<void> {\n\t\tconst entryGroup = await this.resolveEntryTranslationGroup(collection, entryId);\n\t\tif (!entryGroup) return;\n\n\t\tconst groups: string[] = [];\n\t\tfor (const id of termIds) {\n\t\t\tconst group = await this.resolveTranslationGroup(id);\n\t\t\tif (group) groups.push(group);\n\t\t}\n\t\tconst newGroups = new Set(groups);\n\n\t\tconst current = await this.db\n\t\t\t.selectFrom(\"content_taxonomies\")\n\t\t\t.innerJoin(\"taxonomies\", \"taxonomies.translation_group\", \"content_taxonomies.taxonomy_id\")\n\t\t\t.select([\"content_taxonomies.taxonomy_id as group\"])\n\t\t\t.distinct()\n\t\t\t.where(\"content_taxonomies.collection\", \"=\", collection)\n\t\t\t.where(\"content_taxonomies.entry_id\", \"=\", entryGroup)\n\t\t\t.where(\"taxonomies.name\", \"=\", taxonomyName)\n\t\t\t.execute();\n\t\tconst currentGroups = new Set(current.map((r) => r.group));\n\n\t\tconst toRemove = [...currentGroups].filter((g) => !newGroups.has(g));\n\t\tif (toRemove.length > 0) {\n\t\t\tawait this.db\n\t\t\t\t.deleteFrom(\"content_taxonomies\")\n\t\t\t\t.where(\"collection\", \"=\", collection)\n\t\t\t\t.where(\"entry_id\", \"=\", entryGroup)\n\t\t\t\t.where(\"taxonomy_id\", \"in\", toRemove)\n\t\t\t\t.execute();\n\t\t}\n\n\t\tconst toAdd = [...newGroups].filter((g) => !currentGroups.has(g));\n\t\tif (toAdd.length > 0) {\n\t\t\tawait this.db\n\t\t\t\t.insertInto(\"content_taxonomies\")\n\t\t\t\t.values(\n\t\t\t\t\ttoAdd.map((taxonomy_id) => ({\n\t\t\t\t\t\tcollection,\n\t\t\t\t\t\tentry_id: entryGroup,\n\t\t\t\t\t\ttaxonomy_id,\n\t\t\t\t\t})),\n\t\t\t\t)\n\t\t\t\t.onConflict((oc) => oc.doNothing())\n\t\t\t\t.execute();\n\t\t}\n\n\t\tif (toRemove.length > 0 || toAdd.length > 0) invalidateTaxonomyObjectCache();\n\t}\n\n\tasync clearEntryTerms(collection: string, entryId: string): Promise<number> {\n\t\tconst entryGroup = await this.resolveEntryTranslationGroup(collection, entryId);\n\t\tif (!entryGroup) return 0;\n\n\t\tconst result = await this.db\n\t\t\t.deleteFrom(\"content_taxonomies\")\n\t\t\t.where(\"collection\", \"=\", collection)\n\t\t\t.where(\"entry_id\", \"=\", entryGroup)\n\t\t\t.executeTakeFirst();\n\t\tconst removed = Number(result.numDeletedRows ?? 0);\n\t\tif (removed > 0) invalidateTaxonomyObjectCache();\n\t\treturn removed;\n\t}\n\n\tprivate async resolveEntryTranslationGroup(\n\t\tcollection: string,\n\t\tentryIdOrGroup: string,\n\t): Promise<string | null> {\n\t\tvalidateIdentifier(collection, \"collection type\");\n\t\tconst tableName = `ec_${collection}`;\n\t\tconst result = await sql<{ translation_group: string }>`\n\t\t\tSELECT translation_group\n\t\t\tFROM ${sql.ref(tableName)}\n\t\t\tWHERE id = ${entryIdOrGroup} OR translation_group = ${entryIdOrGroup}\n\t\t\tLIMIT 1\n\t\t`.execute(this.db);\n\t\treturn result.rows[0]?.translation_group ?? null;\n\t}\n\n\t/**\n\t * Count content entries that use any translation of this term. Accepts\n\t * either a term id or a translation_group — we normalise to the group.\n\t *\n\t * Counts raw pivot rows regardless of the entry's status or deletion —\n\t * drafts and trashed entries are included. User-facing counts (admin term\n\t * list/get, public widget and term pages) use `fetchVisibleTermCounts`\n\t * from `taxonomies/term-counts.ts` instead, which counts only publicly\n\t * visible entries.\n\t */\n\tasync countEntriesWithTerm(termIdOrGroup: string): Promise<number> {\n\t\tconst group = await this.resolveTranslationGroup(termIdOrGroup);\n\t\tif (!group) return 0;\n\n\t\tconst result = await this.db\n\t\t\t.selectFrom(\"content_taxonomies\")\n\t\t\t.select((eb) => eb.fn.count(\"entry_id\").as(\"count\"))\n\t\t\t.where(\"taxonomy_id\", \"=\", group)\n\t\t\t.executeTakeFirst();\n\t\treturn Number(result?.count ?? 0);\n\t}\n\n\t/**\n\t * Resolve a parent reference (a row id or a translation_group) to the value\n\t * persisted in `parent_id`: the parent's translation_group, which is\n\t * locale-agnostic so the child stays nested in every locale. A\n\t * translation_group normally equals its anchor row's id, which satisfies the\n\t * self-FK on `parent_id`. If that anchor row is missing (a translation whose\n\t * anchor was deleted), fall back to the id we were given so we never write a\n\t * dangling FK value.\n\t */\n\tprivate async resolveParentRef(idOrGroup: string): Promise<string> {\n\t\tconst group = await this.resolveTranslationGroup(idOrGroup);\n\t\tif (!group) return idOrGroup;\n\t\tconst anchor = await this.db\n\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t.select(\"id\")\n\t\t\t.where(\"id\", \"=\", group)\n\t\t\t.executeTakeFirst();\n\t\treturn anchor ? group : idOrGroup;\n\t}\n\n\tprivate async resolveTranslationGroup(idOrGroup: string): Promise<string | null> {\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t.select([\"translation_group\"])\n\t\t\t.where((eb) => eb.or([eb(\"id\", \"=\", idOrGroup), eb(\"translation_group\", \"=\", idOrGroup)]))\n\t\t\t.executeTakeFirst();\n\t\treturn row?.translation_group ?? null;\n\t}\n\n\t/**\n\t * Batch count entries for multiple taxonomy translation_groups.\n\t * Chunks the query at SQL_BATCH_SIZE to stay below D1's bind-parameter limit.\n\t * Returns a Map from translation_group to count.\n\t *\n\t * Pass translation_groups (not term ids) — `content_taxonomies.taxonomy_id`\n\t * stores the translation_group so a single assignment spans every locale.\n\t *\n\t * Like `countEntriesWithTerm`, this counts raw pivot rows regardless of\n\t * status/deletion; user-facing counts go through `fetchVisibleTermCounts`.\n\t */\n\tasync countEntriesForTerms(translationGroups: string[]): Promise<Map<string, number>> {\n\t\tif (translationGroups.length === 0) return new Map();\n\n\t\tconst { chunks, SQL_BATCH_SIZE } = await import(\"../../utils/chunks.js\");\n\n\t\tconst counts = new Map<string, number>();\n\t\tfor (const chunk of chunks(translationGroups, SQL_BATCH_SIZE)) {\n\t\t\tconst rows = await this.db\n\t\t\t\t.selectFrom(\"content_taxonomies\")\n\t\t\t\t.select([\"taxonomy_id\", (eb) => eb.fn.count(\"entry_id\").as(\"count\")])\n\t\t\t\t.where(\"taxonomy_id\", \"in\", chunk)\n\t\t\t\t.groupBy(\"taxonomy_id\")\n\t\t\t\t.execute();\n\n\t\t\tfor (const row of rows) {\n\t\t\t\tcounts.set(row.taxonomy_id, Number(row.count || 0));\n\t\t\t}\n\t\t}\n\t\treturn counts;\n\t}\n\n\tprivate rowToTaxonomy(row: Selectable<TaxonomyTable>): Taxonomy {\n\t\treturn {\n\t\t\tid: row.id,\n\t\t\tname: row.name,\n\t\t\tslug: row.slug,\n\t\t\tlabel: row.label,\n\t\t\tparentId: row.parent_id,\n\t\t\tdata: row.data ? JSON.parse(row.data) : null,\n\t\t\tlocale: row.locale,\n\t\t\ttranslationGroup: row.translation_group,\n\t\t\tsortOrder: row.sort_order,\n\t\t};\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;AAoBA,MAAM,oBAAoB;AAC1B,MAAM,yBAAyB;;AAG/B,SAAS,mBACR,QACA,UACsB;CACtB,M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,CAAC,GAAG,MAAM,KAAK,UAAU,EAAE,GAAG,qBAAqB,KAAK,UAAU,CAAC,CAAC,CAAC,CACzF,kBAAkB,GACR,qBAAqB;;;;;;;;;;;;;CAclC,MAAM,qBAAqB,mBAA2D;AACrF,MAAI,kBAAkB,WAAW,EAAG,wBAAO,IAAI,KAAK;EAEpD,MAAM,EAAE,QAAQ,mBAAmB,MAAM,OAAO;EAEhD,MAAM,yBAAS,IAAI,KAAqB;AACxC,OAAK,MAAM,SAAS,OAAO,mBAAmB,eAAe,EAAE;GAC9D,MAAM,OAAO,MAAM,KAAK,GACtB,WAAW,qBAAqB,CAChC,OAAO,CAAC,gBAAgB,OAAO,GAAG,GAAG,MAAM,WAAW,CAAC,GAAG,QAAQ,CAAC,CAAC,CACpE,MAAM,eAAe,MAAM,MAAM,CACjC,QAAQ,cAAc,CACtB,SAAS;AAEX,QAAK,MAAM,OAAO,KACjB,QAAO,IAAI,IAAI,aAAa,OAAO,IAAI,SAAS,EAAE,CAAC;;AAGrD,SAAO;;CAGR,AAAQ,cAAc,KAA0C;AAC/D,SAAO;GACN,IAAI,IAAI;GACR,MAAM,IAAI;GACV,MAAM,IAAI;GACV,OAAO,IAAI;GACX,UAAU,IAAI;GACd,MAAM,IAAI,OAAO,KAAK,MAAM,IAAI,KAAK,GAAG;GACxC,QAAQ,IAAI;GACZ,kBAAkB,IAAI;GACtB,WAAW,IAAI;GACf"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tokens-C39klX8R.mjs","names":[],"sources":["../src/preview/tokens.ts"],"sourcesContent":["/**\n * Preview token generation and verification\n *\n * Tokens are compact, URL-safe, and HMAC-signed.\n * Format: base64url(JSON payload).base64url(HMAC signature)\n *\n * Payload: { cid: contentId, exp: expiryTimestamp, iat: issuedAt }\n */\n\nimport { encodeBase64url, decodeBase64url } from \"../utils/base64.js\";\n\n// Regex pattern for duration parsing\nconst DURATION_PATTERN = /^(\\d+)([smhdw])$/;\n\n/**\n * Preview token payload\n */\nexport interface PreviewTokenPayload {\n\t/** Content ID in format \"collection:id\" (e.g., \"posts:abc123\") */\n\tcid: string;\n\t/** Expiry timestamp (seconds since epoch) */\n\texp: number;\n\t/** Issued at timestamp (seconds since epoch) */\n\tiat: number;\n}\n\n/**\n * Options for generating a preview token\n */\nexport interface GeneratePreviewTokenOptions {\n\t/** Content ID in format \"collection:id\" */\n\tcontentId: string;\n\t/** How long the token is valid. Accepts \"1h\", \"30m\", \"1d\", or seconds as number. Default: \"1h\" */\n\texpiresIn?: string | number;\n\t/** Secret key for signing. Should be from environment variable. */\n\tsecret: string;\n}\n\n/**\n * Parse duration string to seconds\n * Supports: \"1h\", \"30m\", \"1d\", \"2w\", or raw seconds\n */\nfunction parseDuration(duration: string | number): number {\n\tif (typeof duration === \"number\") {\n\t\treturn duration;\n\t}\n\n\tconst match = duration.match(DURATION_PATTERN);\n\tif (!match) {\n\t\tthrow new Error(\n\t\t\t`Invalid duration format: \"${duration}\". Use \"1h\", \"30m\", \"1d\", \"2w\", or seconds.`,\n\t\t);\n\t}\n\n\tconst value = parseInt(match[1], 10);\n\tconst unit = match[2];\n\n\tswitch (unit) {\n\t\tcase \"s\":\n\t\t\treturn value;\n\t\tcase \"m\":\n\t\t\treturn value * 60;\n\t\tcase \"h\":\n\t\t\treturn value * 60 * 60;\n\t\tcase \"d\":\n\t\t\treturn value * 60 * 60 * 24;\n\t\tcase \"w\":\n\t\t\treturn value * 60 * 60 * 24 * 7;\n\t\tdefault:\n\t\t\tthrow new Error(`Unknown duration unit: ${unit}`);\n\t}\n}\n\n/**\n * Create HMAC-SHA256 signature using Web Crypto API\n */\nasync function createSignature(data: string, secret: string): Promise<Uint8Array> {\n\tconst encoder = new TextEncoder();\n\tconst key = await crypto.subtle.importKey(\n\t\t\"raw\",\n\t\tencoder.encode(secret),\n\t\t{ name: \"HMAC\", hash: \"SHA-256\" },\n\t\tfalse,\n\t\t[\"sign\"],\n\t);\n\tconst signature = await crypto.subtle.sign(\"HMAC\", key, encoder.encode(data));\n\treturn new Uint8Array(signature);\n}\n\n/**\n * Verify HMAC-SHA256 signature\n */\nasync function verifySignature(\n\tdata: string,\n\tsignature: Uint8Array,\n\tsecret: string,\n): Promise<boolean> {\n\tconst encoder = new TextEncoder();\n\tconst key = await crypto.subtle.importKey(\n\t\t\"raw\",\n\t\tencoder.encode(secret),\n\t\t{ name: \"HMAC\", hash: \"SHA-256\" },\n\t\tfalse,\n\t\t[\"verify\"],\n\t);\n\t// Create a new ArrayBuffer from the signature to satisfy BufferSource typing\n\t// (Uint8Array.buffer is ArrayBufferLike which includes SharedArrayBuffer)\n\tconst sigBuffer: ArrayBuffer = new ArrayBuffer(signature.byteLength);\n\tnew Uint8Array(sigBuffer).set(signature);\n\treturn crypto.subtle.verify(\"HMAC\", key, sigBuffer, encoder.encode(data));\n}\n\n/**\n * Generate a preview token for content\n *\n * @example\n * ```ts\n * const token = await generatePreviewToken({\n * contentId: \"posts:abc123\",\n * expiresIn: \"1h\",\n * secret: process.env.PREVIEW_SECRET!,\n * });\n * ```\n */\nexport async function generatePreviewToken(options: GeneratePreviewTokenOptions): Promise<string> {\n\tconst { contentId, expiresIn = \"1h\", secret } = options;\n\n\tif (!secret) {\n\t\tthrow new Error(\"Preview secret is required\");\n\t}\n\n\tif (!contentId || !contentId.includes(\":\")) {\n\t\tthrow new Error('Content ID must be in format \"collection:id\"');\n\t}\n\n\tconst now = Math.floor(Date.now() / 1000);\n\tconst duration = parseDuration(expiresIn);\n\n\tconst payload: PreviewTokenPayload = {\n\t\tcid: contentId,\n\t\texp: now + duration,\n\t\tiat: now,\n\t};\n\n\t// Encode payload\n\tconst payloadJson = JSON.stringify(payload);\n\tconst encodedPayload = encodeBase64url(new TextEncoder().encode(payloadJson));\n\n\t// Sign it\n\tconst signature = await createSignature(encodedPayload, secret);\n\tconst encodedSignature = encodeBase64url(signature);\n\n\treturn `${encodedPayload}.${encodedSignature}`;\n}\n\n/**\n * Result of verifying a preview token\n */\nexport type VerifyPreviewTokenResult =\n\t| { valid: true; payload: PreviewTokenPayload }\n\t| { valid: false; error: \"invalid\" | \"expired\" | \"malformed\" | \"none\" };\n\n/**\n * Options for verifyPreviewToken\n */\nexport type VerifyPreviewTokenOptions = {\n\t/** Secret key for verifying tokens */\n\tsecret: string;\n} & (\n\t| { /** URL to extract _preview token from */ url: URL }\n\t| {\n\t\t\t/** Preview token string (can be null) */ token: string | null | undefined;\n\t }\n);\n\n/**\n * Verify a preview token and return the payload\n *\n * @example\n * ```ts\n * // With URL (extracts _preview query param)\n * const result = await verifyPreviewToken({\n * url: Astro.url,\n * secret: import.meta.env.PREVIEW_SECRET,\n * });\n *\n * // With token directly\n * const result = await verifyPreviewToken({\n * token: someToken,\n * secret: import.meta.env.PREVIEW_SECRET,\n * });\n *\n * if (result.valid) {\n * console.log(result.payload.cid); // \"posts:abc123\"\n * }\n * ```\n */\nexport async function verifyPreviewToken(\n\toptions: VerifyPreviewTokenOptions,\n): Promise<VerifyPreviewTokenResult> {\n\tconst { secret } = options;\n\n\tif (!secret) {\n\t\tthrow new Error(\"Preview secret is required\");\n\t}\n\n\t// Extract token from URL or use provided token\n\tconst token = \"url\" in options ? options.url.searchParams.get(\"_preview\") : options.token;\n\n\t// Handle null/undefined token\n\tif (!token) {\n\t\treturn { valid: false, error: \"none\" };\n\t}\n\n\t// Split token into payload and signature\n\tconst parts = token.split(\".\");\n\tif (parts.length !== 2) {\n\t\treturn { valid: false, error: \"malformed\" };\n\t}\n\n\tconst [encodedPayload, encodedSignature] = parts;\n\n\t// Verify signature\n\tlet signature: Uint8Array;\n\ttry {\n\t\tsignature = decodeBase64url(encodedSignature);\n\t} catch {\n\t\treturn { valid: false, error: \"malformed\" };\n\t}\n\n\tconst isValid = await verifySignature(encodedPayload, signature, secret);\n\tif (!isValid) {\n\t\treturn { valid: false, error: \"invalid\" };\n\t}\n\n\t// Decode and parse payload\n\tlet payload: PreviewTokenPayload;\n\ttry {\n\t\tconst payloadBytes = decodeBase64url(encodedPayload);\n\t\tconst payloadJson = new TextDecoder().decode(payloadBytes);\n\t\tpayload = JSON.parse(payloadJson);\n\t} catch {\n\t\treturn { valid: false, error: \"malformed\" };\n\t}\n\n\t// Check required fields\n\tif (\n\t\ttypeof payload.cid !== \"string\" ||\n\t\ttypeof payload.exp !== \"number\" ||\n\t\ttypeof payload.iat !== \"number\"\n\t) {\n\t\treturn { valid: false, error: \"malformed\" };\n\t}\n\n\t// Check expiry\n\tconst now = Math.floor(Date.now() / 1000);\n\tif (payload.exp < now) {\n\t\treturn { valid: false, error: \"expired\" };\n\t}\n\n\treturn { valid: true, payload };\n}\n\n/**\n * Parse a content ID into collection and id\n */\nexport function parseContentId(contentId: string): {\n\tcollection: string;\n\tid: string;\n} {\n\tconst colonIndex = contentId.indexOf(\":\");\n\tif (colonIndex === -1) {\n\t\tthrow new Error('Content ID must be in format \"collection:id\"');\n\t}\n\treturn {\n\t\tcollection: contentId.slice(0, colonIndex),\n\t\tid: contentId.slice(colonIndex + 1),\n\t};\n}\n"],"mappings":";;;;;;;;;;;AAYA,MAAM,mBAAmB;;;;;AA8BzB,SAAS,cAAc,UAAmC;AACzD,KAAI,OAAO,aAAa,SACvB,QAAO;CAGR,MAAM,QAAQ,SAAS,MAAM,iBAAiB;AAC9C,KAAI,CAAC,MACJ,OAAM,IAAI,MACT,6BAA6B,SAAS,6CACtC;CAGF,MAAM,QAAQ,SAAS,MAAM,IAAI,GAAG;CACpC,MAAM,OAAO,MAAM;AAEnB,SAAQ,MAAR;EACC,KAAK,IACJ,QAAO;EACR,KAAK,IACJ,QAAO,QAAQ;EAChB,KAAK,IACJ,QAAO,QAAQ,KAAK;EACrB,KAAK,IACJ,QAAO,QAAQ,KAAK,KAAK;EAC1B,KAAK,IACJ,QAAO,QAAQ,KAAK,KAAK,KAAK;EAC/B,QACC,OAAM,IAAI,MAAM,0BAA0B,OAAO;;;;;;AAOpD,eAAe,gBAAgB,MAAc,QAAqC;CACjF,MAAM,UAAU,IAAI,aAAa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-gTS-IVUp.mjs","names":[],"sources":["../src/preview/tokens.ts"],"sourcesContent":["/**\n * Preview token generation and verification\n *\n * Tokens are compact, URL-safe, and HMAC-signed.\n * Format: base64url(JSON payload).base64url(HMAC signature)\n *\n * Payload: { cid: contentId, exp: expiryTimestamp, iat: issuedAt }\n */\n\nimport { encodeBase64url, decodeBase64url } from \"../utils/base64.js\";\n\n// Regex pattern for duration parsing\nconst DURATION_PATTERN = /^(\\d+)([smhdw])$/;\n\n/**\n * Preview token payload\n */\nexport interface PreviewTokenPayload {\n\t/** Content ID in format \"collection:id\" (e.g., \"posts:abc123\") */\n\tcid: string;\n\t/** Expiry timestamp (seconds since epoch) */\n\texp: number;\n\t/** Issued at timestamp (seconds since epoch) */\n\tiat: number;\n}\n\n/**\n * Options for generating a preview token\n */\nexport interface GeneratePreviewTokenOptions {\n\t/** Content ID in format \"collection:id\" */\n\tcontentId: string;\n\t/** How long the token is valid. Accepts \"1h\", \"30m\", \"1d\", or seconds as number. Default: \"1h\" */\n\texpiresIn?: string | number;\n\t/** Secret key for signing. Should be from environment variable. */\n\tsecret: string;\n}\n\n/**\n * Parse duration string to seconds\n * Supports: \"1h\", \"30m\", \"1d\", \"2w\", or raw seconds\n */\nfunction parseDuration(duration: string | number): number {\n\tif (typeof duration === \"number\") {\n\t\treturn duration;\n\t}\n\n\tconst match = duration.match(DURATION_PATTERN);\n\tif (!match) {\n\t\tthrow new Error(\n\t\t\t`Invalid duration format: \"${duration}\". Use \"1h\", \"30m\", \"1d\", \"2w\", or seconds.`,\n\t\t);\n\t}\n\n\tconst value = parseInt(match[1], 10);\n\tconst unit = match[2];\n\n\tswitch (unit) {\n\t\tcase \"s\":\n\t\t\treturn value;\n\t\tcase \"m\":\n\t\t\treturn value * 60;\n\t\tcase \"h\":\n\t\t\treturn value * 60 * 60;\n\t\tcase \"d\":\n\t\t\treturn value * 60 * 60 * 24;\n\t\tcase \"w\":\n\t\t\treturn value * 60 * 60 * 24 * 7;\n\t\tdefault:\n\t\t\tthrow new Error(`Unknown duration unit: ${unit}`);\n\t}\n}\n\n/**\n * Create HMAC-SHA256 signature using Web Crypto API\n */\nasync function createSignature(data: string, secret: string): Promise<Uint8Array> {\n\tconst encoder = new TextEncoder();\n\tconst key = await crypto.subtle.importKey(\n\t\t\"raw\",\n\t\tencoder.encode(secret),\n\t\t{ name: \"HMAC\", hash: \"SHA-256\" },\n\t\tfalse,\n\t\t[\"sign\"],\n\t);\n\tconst signature = await crypto.subtle.sign(\"HMAC\", key, encoder.encode(data));\n\treturn new Uint8Array(signature);\n}\n\n/**\n * Verify HMAC-SHA256 signature\n */\nasync function verifySignature(\n\tdata: string,\n\tsignature: Uint8Array,\n\tsecret: string,\n): Promise<boolean> {\n\tconst encoder = new TextEncoder();\n\tconst key = await crypto.subtle.importKey(\n\t\t\"raw\",\n\t\tencoder.encode(secret),\n\t\t{ name: \"HMAC\", hash: \"SHA-256\" },\n\t\tfalse,\n\t\t[\"verify\"],\n\t);\n\t// Create a new ArrayBuffer from the signature to satisfy BufferSource typing\n\t// (Uint8Array.buffer is ArrayBufferLike which includes SharedArrayBuffer)\n\tconst sigBuffer: ArrayBuffer = new ArrayBuffer(signature.byteLength);\n\tnew Uint8Array(sigBuffer).set(signature);\n\treturn crypto.subtle.verify(\"HMAC\", key, sigBuffer, encoder.encode(data));\n}\n\n/**\n * Generate a preview token for content\n *\n * @example\n * ```ts\n * const token = await generatePreviewToken({\n * contentId: \"posts:abc123\",\n * expiresIn: \"1h\",\n * secret: process.env.PREVIEW_SECRET!,\n * });\n * ```\n */\nexport async function generatePreviewToken(options: GeneratePreviewTokenOptions): Promise<string> {\n\tconst { contentId, expiresIn = \"1h\", secret } = options;\n\n\tif (!secret) {\n\t\tthrow new Error(\"Preview secret is required\");\n\t}\n\n\tif (!contentId || !contentId.includes(\":\")) {\n\t\tthrow new Error('Content ID must be in format \"collection:id\"');\n\t}\n\n\tconst now = Math.floor(Date.now() / 1000);\n\tconst duration = parseDuration(expiresIn);\n\n\tconst payload: PreviewTokenPayload = {\n\t\tcid: contentId,\n\t\texp: now + duration,\n\t\tiat: now,\n\t};\n\n\t// Encode payload\n\tconst payloadJson = JSON.stringify(payload);\n\tconst encodedPayload = encodeBase64url(new TextEncoder().encode(payloadJson));\n\n\t// Sign it\n\tconst signature = await createSignature(encodedPayload, secret);\n\tconst encodedSignature = encodeBase64url(signature);\n\n\treturn `${encodedPayload}.${encodedSignature}`;\n}\n\n/**\n * Result of verifying a preview token\n */\nexport type VerifyPreviewTokenResult =\n\t| { valid: true; payload: PreviewTokenPayload }\n\t| { valid: false; error: \"invalid\" | \"expired\" | \"malformed\" | \"none\" };\n\n/**\n * Options for verifyPreviewToken\n */\nexport type VerifyPreviewTokenOptions = {\n\t/** Secret key for verifying tokens */\n\tsecret: string;\n} & (\n\t| { /** URL to extract _preview token from */ url: URL }\n\t| {\n\t\t\t/** Preview token string (can be null) */ token: string | null | undefined;\n\t }\n);\n\n/**\n * Verify a preview token and return the payload\n *\n * @example\n * ```ts\n * // With URL (extracts _preview query param)\n * const result = await verifyPreviewToken({\n * url: Astro.url,\n * secret: import.meta.env.PREVIEW_SECRET,\n * });\n *\n * // With token directly\n * const result = await verifyPreviewToken({\n * token: someToken,\n * secret: import.meta.env.PREVIEW_SECRET,\n * });\n *\n * if (result.valid) {\n * console.log(result.payload.cid); // \"posts:abc123\"\n * }\n * ```\n */\nexport async function verifyPreviewToken(\n\toptions: VerifyPreviewTokenOptions,\n): Promise<VerifyPreviewTokenResult> {\n\tconst { secret } = options;\n\n\tif (!secret) {\n\t\tthrow new Error(\"Preview secret is required\");\n\t}\n\n\t// Extract token from URL or use provided token\n\tconst token = \"url\" in options ? options.url.searchParams.get(\"_preview\") : options.token;\n\n\t// Handle null/undefined token\n\tif (!token) {\n\t\treturn { valid: false, error: \"none\" };\n\t}\n\n\t// Split token into payload and signature\n\tconst parts = token.split(\".\");\n\tif (parts.length !== 2) {\n\t\treturn { valid: false, error: \"malformed\" };\n\t}\n\n\tconst [encodedPayload, encodedSignature] = parts;\n\n\t// Verify signature\n\tlet signature: Uint8Array;\n\ttry {\n\t\tsignature = decodeBase64url(encodedSignature);\n\t} catch {\n\t\treturn { valid: false, error: \"malformed\" };\n\t}\n\n\tconst isValid = await verifySignature(encodedPayload, signature, secret);\n\tif (!isValid) {\n\t\treturn { valid: false, error: \"invalid\" };\n\t}\n\n\t// Decode and parse payload\n\tlet payload: PreviewTokenPayload;\n\ttry {\n\t\tconst payloadBytes = decodeBase64url(encodedPayload);\n\t\tconst payloadJson = new TextDecoder().decode(payloadBytes);\n\t\tpayload = JSON.parse(payloadJson);\n\t} catch {\n\t\treturn { valid: false, error: \"malformed\" };\n\t}\n\n\t// Check required fields\n\tif (\n\t\ttypeof payload.cid !== \"string\" ||\n\t\ttypeof payload.exp !== \"number\" ||\n\t\ttypeof payload.iat !== \"number\"\n\t) {\n\t\treturn { valid: false, error: \"malformed\" };\n\t}\n\n\t// Check expiry\n\tconst now = Math.floor(Date.now() / 1000);\n\tif (payload.exp < now) {\n\t\treturn { valid: false, error: \"expired\" };\n\t}\n\n\treturn { valid: true, payload };\n}\n\n/**\n * Parse a content ID into collection and id\n */\nexport function parseContentId(contentId: string): {\n\tcollection: string;\n\tid: string;\n} {\n\tconst colonIndex = contentId.indexOf(\":\");\n\tif (colonIndex === -1) {\n\t\tthrow new Error('Content ID must be in format \"collection:id\"');\n\t}\n\treturn {\n\t\tcollection: contentId.slice(0, colonIndex),\n\t\tid: contentId.slice(colonIndex + 1),\n\t};\n}\n"],"mappings":";;;;;;;;;;;AAYA,MAAM,mBAAmB;;;;;AA8BzB,SAAS,cAAc,UAAmC;AACzD,KAAI,OAAO,aAAa,SACvB,QAAO;CAGR,MAAM,QAAQ,SAAS,MAAM,iBAAiB;AAC9C,KAAI,CAAC,MACJ,OAAM,IAAI,MACT,6BAA6B,SAAS,6CACtC;CAGF,MAAM,QAAQ,SAAS,MAAM,IAAI,GAAG;CACpC,MAAM,OAAO,MAAM;AAEnB,SAAQ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AAE,OAAO;EAAO,OAAO;EAAW;AAG1C,QAAO;EAAE,OAAO;EAAM;EAAS;;;;;AAMhC,SAAgB,eAAe,WAG7B;CACD,MAAM,aAAa,UAAU,QAAQ,IAAI;AACzC,KAAI,eAAe,GAClB,OAAM,IAAI,MAAM,iDAA+C;AAEhE,QAAO;EACN,YAAY,UAAU,MAAM,GAAG,WAAW;EAC1C,IAAI,UAAU,MAAM,aAAa,EAAE;EACnC"}
|
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
let transactionsSupported = null;
|
|
9
9
|
const TRANSACTIONS_NOT_SUPPORTED_RE = /transactions are not supported/i;
|
|
10
10
|
async function withTransaction(db, fn) {
|
|
11
|
+
if (db.isTransaction) return fn(db);
|
|
11
12
|
if (transactionsSupported === true) return db.transaction().execute(fn);
|
|
12
13
|
if (transactionsSupported === false) return fn(db);
|
|
13
14
|
try {
|
|
@@ -25,4 +26,4 @@ async function withTransaction(db, fn) {
|
|
|
25
26
|
|
|
26
27
|
//#endregion
|
|
27
28
|
export { withTransaction as t };
|
|
28
|
-
//# sourceMappingURL=transaction-
|
|
29
|
+
//# sourceMappingURL=transaction-0KOpOyMu.mjs.map
|