emdash 0.30.0 → 0.31.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/route-utils.mjs +13 -13
- package/dist/api/schemas/index.d.mts +1 -1
- package/dist/api/schemas/index.mjs +3 -3
- package/dist/{api-b8WIiGU4.mjs → api-BkqFzIu4.mjs} +23 -23
- package/dist/api-BkqFzIu4.mjs.map +1 -0
- package/dist/{apply-CmIJK9j8.mjs → apply-DuXsqll7.mjs} +26 -25
- package/dist/apply-DuXsqll7.mjs.map +1 -0
- package/dist/astro/index.d.mts +2 -2
- package/dist/astro/index.mjs +1 -1
- package/dist/astro/middleware/auth.d.mts +2 -2
- package/dist/astro/middleware/auth.mjs +2 -2
- package/dist/astro/middleware/redirect.mjs +5 -5
- package/dist/astro/middleware/request-context.mjs +1 -1
- package/dist/astro/middleware.d.mts +2 -2
- package/dist/astro/middleware.mjs +146 -70
- 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 +2 -2
- package/dist/astro/routes/api/admin/api-tokens/index.mjs +3 -3
- package/dist/astro/routes/api/admin/byline-fields/_slug_/usage.mjs +3 -3
- package/dist/astro/routes/api/admin/byline-fields/_slug_.mjs +7 -7
- package/dist/astro/routes/api/admin/byline-fields/index.mjs +7 -7
- package/dist/astro/routes/api/admin/byline-fields/reorder.mjs +7 -7
- package/dist/astro/routes/api/admin/bylines/_id_/index.mjs +14 -14
- package/dist/astro/routes/api/admin/bylines/_id_/translations.mjs +14 -14
- package/dist/astro/routes/api/admin/bylines/index.d.mts.map +1 -1
- package/dist/astro/routes/api/admin/bylines/index.mjs +18 -17
- package/dist/astro/routes/api/admin/bylines/index.mjs.map +1 -1
- package/dist/astro/routes/api/admin/comments/_id_/status.mjs +10 -10
- package/dist/astro/routes/api/admin/comments/_id_.mjs +5 -5
- package/dist/astro/routes/api/admin/comments/bulk.mjs +9 -9
- package/dist/astro/routes/api/admin/comments/counts.mjs +5 -5
- 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/repair.mjs +10 -10
- 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 +34 -34
- package/dist/astro/routes/api/admin/plugins/_id_/enable.mjs +34 -34
- package/dist/astro/routes/api/admin/plugins/_id_/index.mjs +34 -34
- package/dist/astro/routes/api/admin/plugins/_id_/mcp.mjs +4 -4
- package/dist/astro/routes/api/admin/plugins/_id_/settings.mjs +34 -34
- package/dist/astro/routes/api/admin/plugins/_id_/uninstall.mjs +34 -34
- package/dist/astro/routes/api/admin/plugins/_id_/update.mjs +34 -34
- package/dist/astro/routes/api/admin/plugins/index.mjs +34 -34
- package/dist/astro/routes/api/admin/plugins/marketplace/_id_/icon.mjs +3 -3
- package/dist/astro/routes/api/admin/plugins/marketplace/_id_/index.mjs +34 -34
- package/dist/astro/routes/api/admin/plugins/marketplace/_id_/install.mjs +34 -34
- package/dist/astro/routes/api/admin/plugins/marketplace/index.mjs +34 -34
- package/dist/astro/routes/api/admin/plugins/registry/_id_/uninstall.mjs +34 -34
- package/dist/astro/routes/api/admin/plugins/registry/_id_/update.mjs +35 -35
- package/dist/astro/routes/api/admin/plugins/registry/artifact.mjs +34 -34
- package/dist/astro/routes/api/admin/plugins/registry/install.mjs +35 -35
- package/dist/astro/routes/api/admin/plugins/updates.mjs +34 -34
- package/dist/astro/routes/api/admin/themes/marketplace/_id_/index.mjs +34 -34
- package/dist/astro/routes/api/admin/themes/marketplace/_id_/thumbnail.mjs +3 -3
- package/dist/astro/routes/api/admin/themes/marketplace/index.mjs +34 -34
- package/dist/astro/routes/api/admin/users/_id_/disable.mjs +2 -2
- package/dist/astro/routes/api/admin/users/_id_/enable.mjs +2 -2
- package/dist/astro/routes/api/admin/users/_id_/index.mjs +6 -6
- package/dist/astro/routes/api/admin/users/_id_/send-recovery.mjs +2 -2
- package/dist/astro/routes/api/admin/users/index.mjs +6 -6
- package/dist/astro/routes/api/auth/dev-bypass.mjs +4 -4
- package/dist/astro/routes/api/auth/invite/accept.mjs +2 -2
- package/dist/astro/routes/api/auth/invite/complete.mjs +6 -6
- package/dist/astro/routes/api/auth/invite/index.mjs +6 -6
- package/dist/astro/routes/api/auth/invite/register-options.mjs +6 -6
- package/dist/astro/routes/api/auth/logout.mjs +2 -2
- package/dist/astro/routes/api/auth/magic-link/send.mjs +7 -7
- package/dist/astro/routes/api/auth/magic-link/verify.mjs +2 -2
- package/dist/astro/routes/api/auth/me.mjs +7 -7
- package/dist/astro/routes/api/auth/mode.mjs +2 -2
- package/dist/astro/routes/api/auth/passkey/_id_.mjs +6 -6
- package/dist/astro/routes/api/auth/passkey/index.mjs +2 -2
- package/dist/astro/routes/api/auth/passkey/options.mjs +7 -7
- package/dist/astro/routes/api/auth/passkey/register/options.mjs +6 -6
- package/dist/astro/routes/api/auth/passkey/register/verify.mjs +6 -6
- package/dist/astro/routes/api/auth/passkey/verify.mjs +6 -6
- package/dist/astro/routes/api/auth/signup/complete.mjs +6 -6
- package/dist/astro/routes/api/auth/signup/request.mjs +7 -7
- package/dist/astro/routes/api/auth/signup/verify.mjs +2 -2
- package/dist/astro/routes/api/comments/_collection_/_contentId_/index.mjs +10 -10
- package/dist/astro/routes/api/comments/_collection_/_contentId_/reactions.mjs +10 -10
- package/dist/astro/routes/api/content/_collection_/_id_/compare.mjs +3 -3
- 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 +3 -3
- package/dist/astro/routes/api/content/_collection_/_id_/preview-url.mjs +9 -9
- package/dist/astro/routes/api/content/_collection_/_id_/publish.mjs +7 -7
- package/dist/astro/routes/api/content/_collection_/_id_/references/_relation_/children.mjs +14 -14
- package/dist/astro/routes/api/content/_collection_/_id_/references/_relation_/parents.mjs +14 -14
- package/dist/astro/routes/api/content/_collection_/_id_/restore.mjs +3 -3
- package/dist/astro/routes/api/content/_collection_/_id_/revisions.mjs +3 -3
- package/dist/astro/routes/api/content/_collection_/_id_/schedule.mjs +7 -7
- package/dist/astro/routes/api/content/_collection_/_id_/terms/_taxonomy_.mjs +13 -13
- package/dist/astro/routes/api/content/_collection_/_id_/translations.mjs +3 -3
- package/dist/astro/routes/api/content/_collection_/_id_/unpublish.mjs +3 -3
- package/dist/astro/routes/api/content/_collection_/_id_.mjs +7 -7
- package/dist/astro/routes/api/content/_collection_/authors.mjs +3 -3
- package/dist/astro/routes/api/content/_collection_/index.mjs +7 -7
- 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.mjs +12 -12
- package/dist/astro/routes/api/import/wordpress/analyze.mjs +3 -3
- package/dist/astro/routes/api/import/wordpress/execute.d.mts +2 -2
- package/dist/astro/routes/api/import/wordpress/execute.mjs +11 -11
- package/dist/astro/routes/api/import/wordpress/media.d.mts +2 -2
- package/dist/astro/routes/api/import/wordpress/media.mjs +7 -7
- package/dist/astro/routes/api/import/wordpress/prepare.mjs +9 -9
- package/dist/astro/routes/api/import/wordpress/rewrite-urls.d.mts +2 -2
- package/dist/astro/routes/api/import/wordpress/rewrite-urls.mjs +9 -9
- package/dist/astro/routes/api/import/wordpress-plugin/analyze.mjs +12 -12
- package/dist/astro/routes/api/import/wordpress-plugin/execute.d.mts +2 -2
- package/dist/astro/routes/api/import/wordpress-plugin/execute.mjs +19 -19
- package/dist/astro/routes/api/manifest.mjs +3 -3
- package/dist/astro/routes/api/mcp.mjs +39 -39
- package/dist/astro/routes/api/media/_id_/confirm.mjs +7 -7
- package/dist/astro/routes/api/media/_id_/usage.mjs +11 -11
- package/dist/astro/routes/api/media/_id_.mjs +10 -10
- package/dist/astro/routes/api/media/file/_...key_.mjs +2 -2
- package/dist/astro/routes/api/media/providers/_providerId_/_itemId_.mjs +3 -3
- package/dist/astro/routes/api/media/providers/_providerId_/index.mjs +3 -3
- package/dist/astro/routes/api/media/providers/index.mjs +3 -3
- package/dist/astro/routes/api/media/upload-url.mjs +7 -7
- package/dist/astro/routes/api/media.mjs +10 -10
- 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.d.mts.map +1 -1
- package/dist/astro/routes/api/oauth/authorize.mjs +23 -9
- package/dist/astro/routes/api/oauth/authorize.mjs.map +1 -1
- package/dist/astro/routes/api/oauth/device/authorize.mjs +3 -3
- package/dist/astro/routes/api/oauth/device/code.mjs +4 -4
- package/dist/astro/routes/api/oauth/device/token.mjs +4 -4
- package/dist/astro/routes/api/oauth/register.mjs +2 -2
- package/dist/astro/routes/api/oauth/token/refresh.mjs +3 -3
- package/dist/astro/routes/api/oauth/token/revoke.mjs +3 -3
- package/dist/astro/routes/api/oauth/token.mjs +2 -2
- package/dist/astro/routes/api/openapi.json.mjs +4 -4
- 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 +14 -14
- package/dist/astro/routes/api/relations/_id_/translations.mjs +10 -10
- package/dist/astro/routes/api/relations/index.mjs +14 -14
- package/dist/astro/routes/api/revisions/_revisionId_/index.mjs +3 -3
- package/dist/astro/routes/api/revisions/_revisionId_/restore.mjs +3 -3
- package/dist/astro/routes/api/schema/collections/_slug_/fields/_fieldSlug_.mjs +34 -34
- package/dist/astro/routes/api/schema/collections/_slug_/fields/index.mjs +34 -34
- package/dist/astro/routes/api/schema/collections/_slug_/fields/reorder.mjs +34 -34
- package/dist/astro/routes/api/schema/collections/_slug_/index.mjs +34 -34
- package/dist/astro/routes/api/schema/collections/index.mjs +34 -34
- package/dist/astro/routes/api/schema/index.mjs +8 -8
- package/dist/astro/routes/api/schema/orphans/_slug_.mjs +34 -34
- package/dist/astro/routes/api/schema/orphans/index.mjs +34 -34
- package/dist/astro/routes/api/search/enable.mjs +11 -11
- package/dist/astro/routes/api/search/index.mjs +10 -10
- package/dist/astro/routes/api/search/rebuild.mjs +11 -11
- package/dist/astro/routes/api/search/stats.mjs +7 -7
- package/dist/astro/routes/api/search/suggest.mjs +10 -10
- package/dist/astro/routes/api/sections/_slug_.mjs +10 -10
- package/dist/astro/routes/api/sections/index.mjs +10 -10
- package/dist/astro/routes/api/settings/backups/archives/_name_.mjs +4 -4
- package/dist/astro/routes/api/settings/backups/archives/index.mjs +4 -4
- package/dist/astro/routes/api/settings/backups/export.mjs +4 -4
- package/dist/astro/routes/api/settings/backups/index.mjs +5 -5
- package/dist/astro/routes/api/settings/email.mjs +4 -4
- package/dist/astro/routes/api/settings.mjs +12 -12
- package/dist/astro/routes/api/setup/admin-verify.mjs +6 -6
- package/dist/astro/routes/api/setup/admin.mjs +6 -6
- package/dist/astro/routes/api/setup/dev-bypass.mjs +18 -18
- package/dist/astro/routes/api/setup/dev-reset.mjs +2 -2
- package/dist/astro/routes/api/setup/index.mjs +22 -22
- package/dist/astro/routes/api/setup/status.mjs +3 -3
- package/dist/astro/routes/api/snapshot.mjs +4 -4
- 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/index.mjs +13 -13
- package/dist/astro/routes/api/themes/preview.mjs +4 -4
- package/dist/astro/routes/api/typegen.mjs +5 -5
- 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 +6 -6
- 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 +5 -5
- package/dist/astro/routes/sitemap-_collection_.xml.mjs +7 -7
- package/dist/astro/routes/sitemap.xml.mjs +5 -5
- package/dist/astro/types.d.mts +2 -2
- package/dist/{authorize-WxsiePzy.mjs → authorize-6WPZa1xZ.mjs} +2 -2
- package/dist/{authorize-WxsiePzy.mjs.map → authorize-6WPZa1xZ.mjs.map} +1 -1
- package/dist/{backup-S8kFWtwD.mjs → backup-DoW-H0r4.mjs} +2 -2
- package/dist/{backup-S8kFWtwD.mjs.map → backup-DoW-H0r4.mjs.map} +1 -1
- package/dist/{byline-XEjchwzZ.mjs → byline-BTOxUlFF.mjs} +6 -6
- package/dist/{byline-XEjchwzZ.mjs.map → byline-BTOxUlFF.mjs.map} +1 -1
- package/dist/{bylines-czseViYo.mjs → bylines-Bc-3xtpz.mjs} +6 -6
- package/dist/{bylines-czseViYo.mjs.map → bylines-Bc-3xtpz.mjs.map} +1 -1
- package/dist/{bylines-BJbT4gKS.mjs → bylines-oVN0iPwX.mjs} +12 -8
- package/dist/bylines-oVN0iPwX.mjs.map +1 -0
- package/dist/{cache-CGCd6AVM.mjs → cache-DDwy3JDW.mjs} +2 -2
- package/dist/{cache-CGCd6AVM.mjs.map → cache-DDwy3JDW.mjs.map} +1 -1
- package/dist/{chunks-BxXyunY-.mjs → chunks-Bq-5DPrD.mjs} +2 -2
- package/dist/{chunks-BxXyunY-.mjs.map → chunks-Bq-5DPrD.mjs.map} +1 -1
- package/dist/cli/index.mjs +18 -18
- package/dist/{comment-DPT0WKyd.mjs → comment-B9cUud8H.mjs} +2 -2
- package/dist/{comment-DPT0WKyd.mjs.map → comment-B9cUud8H.mjs.map} +1 -1
- package/dist/{comment-reaction-C65MldIB.mjs → comment-reaction-VUXO981F.mjs} +2 -2
- package/dist/{comment-reaction-C65MldIB.mjs.map → comment-reaction-VUXO981F.mjs.map} +1 -1
- package/dist/{comments-Bz6sCbgD.mjs → comments-PXj1E9Si.mjs} +3 -3
- package/dist/{comments-Bz6sCbgD.mjs.map → comments-PXj1E9Si.mjs.map} +1 -1
- package/dist/{config-CVssduLe.mjs → config-B6b_BobR.mjs} +6 -2
- package/dist/config-B6b_BobR.mjs.map +1 -0
- package/dist/{content-Ci04z2z-.mjs → content-BC43pICM.mjs} +4 -4
- package/dist/{content-Ci04z2z-.mjs.map → content-BC43pICM.mjs.map} +1 -1
- package/dist/{content-refresh-D4khvC0R.mjs → content-refresh-CPMSauD3.mjs} +4 -4
- package/dist/{content-refresh-D4khvC0R.mjs.map → content-refresh-CPMSauD3.mjs.map} +1 -1
- package/dist/{context-B6hc7zJL.mjs → context-DOurRIrb.mjs} +10 -10
- package/dist/{context-B6hc7zJL.mjs.map → context-DOurRIrb.mjs.map} +1 -1
- package/dist/{dashboard-C5NkXFbi.mjs → dashboard-CBm4zhc3.mjs} +4 -4
- package/dist/{dashboard-C5NkXFbi.mjs.map → dashboard-CBm4zhc3.mjs.map} +1 -1
- package/dist/database/pg-migration-lock.d.mts.map +1 -1
- package/dist/database/pg-migration-lock.mjs +1 -4
- package/dist/database/pg-migration-lock.mjs.map +1 -1
- package/dist/db/index.mjs +2 -2
- package/dist/{dialect-helpers-HxEQGl_1.mjs → dialect-helpers-BtOwo2us.mjs} +4 -4
- package/dist/dialect-helpers-BtOwo2us.mjs.map +1 -0
- package/dist/{error-CEGF6UZb.mjs → error-DJ98TRbQ.mjs} +2 -2
- package/dist/{error-CEGF6UZb.mjs.map → error-DJ98TRbQ.mjs.map} +1 -1
- package/dist/{field-defs-cache-DvmlgP-D.mjs → field-defs-cache-KfNJ_qLQ.mjs} +2 -2
- package/dist/{field-defs-cache-DvmlgP-D.mjs.map → field-defs-cache-KfNJ_qLQ.mjs.map} +1 -1
- package/dist/{fts-manager-DzqIBrrW.mjs → fts-manager-hyCU9OOp.mjs} +3 -3
- package/dist/{fts-manager-DzqIBrrW.mjs.map → fts-manager-hyCU9OOp.mjs.map} +1 -1
- package/dist/{hreflang-db2Tpb2o.mjs → hreflang-CbYeCzl9.mjs} +7 -7
- package/dist/{hreflang-db2Tpb2o.mjs.map → hreflang-CbYeCzl9.mjs.map} +1 -1
- package/dist/{import-Dmkm8S1W.mjs → import-oDYCgNYQ.mjs} +2 -2
- package/dist/{import-Dmkm8S1W.mjs.map → import-oDYCgNYQ.mjs.map} +1 -1
- package/dist/{index-wYnC6u4o.d.mts → index-BZJ_5FOX.d.mts} +50 -4
- package/dist/index-BZJ_5FOX.d.mts.map +1 -0
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +48 -48
- package/dist/{load-Cx27ki1l.mjs → load-Dg5gtWma.mjs} +2 -2
- package/dist/{load-Cx27ki1l.mjs.map → load-Dg5gtWma.mjs.map} +1 -1
- package/dist/{loader-Be3ouI5L.mjs → loader-D4rigvjR.mjs} +4 -4
- package/dist/{loader-Be3ouI5L.mjs.map → loader-D4rigvjR.mjs.map} +1 -1
- package/dist/media/local-runtime.d.mts +2 -2
- package/dist/media/local-runtime.mjs +5 -5
- package/dist/{media-kIV1IxFf.mjs → media-BJ6SRY3g.mjs} +8 -4
- package/dist/media-BJ6SRY3g.mjs.map +1 -0
- package/dist/{media-BjhhENaJ.mjs → media-its1WLYv.mjs} +2 -2
- package/dist/{media-BjhhENaJ.mjs.map → media-its1WLYv.mjs.map} +1 -1
- package/dist/{media-upload-D2wk3EIt.mjs → media-upload-DNu3QySc.mjs} +4 -4
- package/dist/{media-upload-D2wk3EIt.mjs.map → media-upload-DNu3QySc.mjs.map} +1 -1
- package/dist/{media-usage-CljdO1mc.mjs → media-usage-DPQ3K4xB.mjs} +6 -6
- package/dist/{media-usage-CljdO1mc.mjs.map → media-usage-DPQ3K4xB.mjs.map} +1 -1
- package/dist/{menus-CZyG6rvx.mjs → menus-BMGzWyWH.mjs} +15 -8
- package/dist/menus-BMGzWyWH.mjs.map +1 -0
- package/dist/{menus-BcyElFtI.mjs → menus-CPf_SW7u.mjs} +86 -8
- package/dist/menus-CPf_SW7u.mjs.map +1 -0
- package/dist/{parse-C_-6klII.mjs → parse-53zyxlpv.mjs} +2 -2
- package/dist/{parse-C_-6klII.mjs.map → parse-53zyxlpv.mjs.map} +1 -1
- package/dist/plugin-utils.d.mts +2 -2
- package/dist/plugins/adapt-sandbox-entry.d.mts +2 -2
- package/dist/{query-DR73ZNfm.mjs → query-Bz9bWZfm.mjs} +14 -14
- package/dist/{query-DR73ZNfm.mjs.map → query-Bz9bWZfm.mjs.map} +1 -1
- package/dist/{query-Di7DOmPV.mjs → query-DdFGHzQF.mjs} +3 -3
- package/dist/{query-Di7DOmPV.mjs.map → query-DdFGHzQF.mjs.map} +1 -1
- package/dist/{rate-limit-CMj83JNW.mjs → rate-limit-D3IEiUi2.mjs} +2 -2
- package/dist/{rate-limit-CMj83JNW.mjs.map → rate-limit-D3IEiUi2.mjs.map} +1 -1
- package/dist/{redirect-CgLPYflR.mjs → redirect-BoUac4NT.mjs} +3 -3
- package/dist/{redirect-CgLPYflR.mjs.map → redirect-BoUac4NT.mjs.map} +1 -1
- package/dist/{redirects-B7t9bKsL.mjs → redirects-ChbpqKiS.mjs} +3 -3
- package/dist/{redirects-B7t9bKsL.mjs.map → redirects-ChbpqKiS.mjs.map} +1 -1
- package/dist/{redirects-BBq3n2Rj.mjs → redirects-D457qwt0.mjs} +8 -8
- package/dist/redirects-D457qwt0.mjs.map +1 -0
- package/dist/{registry-FV15nLge.mjs → registry-y21kjhfG.mjs} +6 -6
- package/dist/{registry-FV15nLge.mjs.map → registry-y21kjhfG.mjs.map} +1 -1
- package/dist/{relation-9M9j_UWo.mjs → relation-Du0r04E0.mjs} +3 -3
- package/dist/{relation-9M9j_UWo.mjs.map → relation-Du0r04E0.mjs.map} +1 -1
- package/dist/{relations-5_avdrN_.mjs → relations-CZMpBqEd.mjs} +3 -3
- package/dist/{relations-5_avdrN_.mjs.map → relations-CZMpBqEd.mjs.map} +1 -1
- package/dist/{relations-BKvO39-9.mjs → relations-DtX1UMBH.mjs} +13 -7
- package/dist/relations-DtX1UMBH.mjs.map +1 -0
- package/dist/{relations-Bh8jlFsU.d.mts → relations-qKmSj9KM.d.mts} +27 -23
- package/dist/relations-qKmSj9KM.d.mts.map +1 -0
- package/dist/{resolve-Cd9dzclN.mjs → resolve-DFr4kq72.mjs} +2 -2
- package/dist/{resolve-Cd9dzclN.mjs.map → resolve-DFr4kq72.mjs.map} +1 -1
- package/dist/{runner-DfnZ5eUr.mjs → runner-BdeLEgad.mjs} +3 -3
- package/dist/{runner-DfnZ5eUr.mjs.map → runner-BdeLEgad.mjs.map} +1 -1
- package/dist/runtime.d.mts +2 -2
- package/dist/runtime.mjs +3 -3
- package/dist/{schema-BXxlHeAf.mjs → schema-BH8P8vaC.mjs} +3 -3
- package/dist/{schema-BXxlHeAf.mjs.map → schema-BH8P8vaC.mjs.map} +1 -1
- package/dist/{scopes-Bl4IwHA-.mjs → scopes-DTIkIaGA.mjs} +2 -2
- package/dist/{scopes-Bl4IwHA-.mjs.map → scopes-DTIkIaGA.mjs.map} +1 -1
- package/dist/{search-Bff-7jFt.mjs → search-D-Yhpmvs.mjs} +8 -7
- package/dist/search-D-Yhpmvs.mjs.map +1 -0
- package/dist/{secrets-CSwQIl4q.mjs → secrets-CQ-69kF9.mjs} +23 -17
- package/dist/secrets-CQ-69kF9.mjs.map +1 -0
- package/dist/{sections-CwW4s1al.mjs → sections-CzVBAKjw.mjs} +3 -3
- package/dist/{sections-CwW4s1al.mjs.map → sections-CzVBAKjw.mjs.map} +1 -1
- package/dist/seed/index.mjs +16 -16
- package/dist/seo/index.mjs +12 -12
- package/dist/{seo-2cmFHZns.mjs → seo-kJzVAmmu.mjs} +2 -2
- package/dist/{seo-2cmFHZns.mjs.map → seo-kJzVAmmu.mjs.map} +1 -1
- package/dist/{service-DkGTWGIi.mjs → service-CQnc276a.mjs} +2 -2
- package/dist/{service-DkGTWGIi.mjs.map → service-CQnc276a.mjs.map} +1 -1
- package/dist/{settings-CpA4lQFt.mjs → settings-C2PaBS49.mjs} +3 -3
- package/dist/{settings-CpA4lQFt.mjs.map → settings-C2PaBS49.mjs.map} +1 -1
- package/dist/{settings-C4s8hFQm.mjs → settings-Dtc0DU31.mjs} +3 -3
- package/dist/{settings-C4s8hFQm.mjs.map → settings-Dtc0DU31.mjs.map} +1 -1
- package/dist/{taxonomies-Ce49uIzY.mjs → taxonomies-BN6M9Nrv.mjs} +26 -17
- package/dist/taxonomies-BN6M9Nrv.mjs.map +1 -0
- package/dist/{taxonomies-DjSKBZpq.mjs → taxonomies-r7pqLBCn.mjs} +53 -24
- package/dist/taxonomies-r7pqLBCn.mjs.map +1 -0
- package/dist/{taxonomy-DfVooU4W.mjs → taxonomy-0mCI25HN.mjs} +3 -3
- package/dist/{taxonomy-DfVooU4W.mjs.map → taxonomy-0mCI25HN.mjs.map} +1 -1
- package/dist/{types-D1iJ3DpO.mjs → types-CrRUFdej.mjs} +2 -2
- package/dist/{types-D1iJ3DpO.mjs.map → types-CrRUFdej.mjs.map} +1 -1
- package/dist/{user-Bh-L1qo6.mjs → user-aTXqmXBz.mjs} +3 -3
- package/dist/{user-Bh-L1qo6.mjs.map → user-aTXqmXBz.mjs.map} +1 -1
- package/dist/{validate-V9nCwq_-.mjs → validate-CDT1jl6_.mjs} +11 -6
- package/dist/validate-CDT1jl6_.mjs.map +1 -0
- package/dist/validate-DULfgpJP.d.mts.map +1 -1
- package/dist/{validation-BsVUJfsP.mjs → validation-DlD0E35W.mjs} +8 -8
- package/dist/{validation-BsVUJfsP.mjs.map → validation-DlD0E35W.mjs.map} +1 -1
- package/dist/version-BRMngh9I.mjs +7 -0
- package/dist/{version-907opKac.mjs.map → version-BRMngh9I.mjs.map} +1 -1
- package/dist/{widgets-DGv1Z04V.mjs → widgets-5fipNkMT.mjs} +2 -2
- package/dist/{widgets-DGv1Z04V.mjs.map → widgets-5fipNkMT.mjs.map} +1 -1
- package/dist/{wxr-taxonomies-Cs1N6O8z.mjs → wxr-taxonomies-DrihupaC.mjs} +4 -4
- package/dist/{wxr-taxonomies-Cs1N6O8z.mjs.map → wxr-taxonomies-DrihupaC.mjs.map} +1 -1
- package/dist/{zod-generator-B5prQ5M4.mjs → zod-generator-CwkHWz4f.mjs} +2 -2
- package/dist/{zod-generator-B5prQ5M4.mjs.map → zod-generator-CwkHWz4f.mjs.map} +1 -1
- package/package.json +7 -7
- package/src/api/handlers/bylines.ts +5 -4
- package/src/api/handlers/content.ts +25 -7
- package/src/api/handlers/menus.ts +11 -6
- package/src/api/handlers/relations.ts +7 -2
- package/src/api/handlers/taxonomies.ts +22 -14
- package/src/api/schemas/bylines.ts +4 -4
- package/src/api/schemas/common.ts +7 -6
- package/src/api/schemas/menus.ts +2 -1
- package/src/api/schemas/relations.ts +3 -1
- package/src/api/schemas/taxonomies.ts +4 -2
- package/src/astro/prefetch.ts +7 -2
- package/src/astro/routes/api/admin/bylines/index.ts +5 -8
- package/src/astro/routes/api/oauth/authorize.ts +42 -10
- package/src/components/Gallery.astro +141 -26
- package/src/components/widgets/Categories.astro +1 -1
- package/src/components/widgets/Tags.astro +1 -1
- package/src/config/secrets.ts +25 -19
- package/src/content/converters/gallery.ts +61 -0
- package/src/content/converters/portable-text-to-prosemirror.ts +19 -0
- package/src/content/converters/prosemirror-to-portable-text.ts +18 -0
- package/src/content/converters/types.ts +36 -0
- package/src/database/dialect-helpers.ts +3 -4
- package/src/database/pg-migration-lock.ts +1 -4
- package/src/emdash-runtime.ts +55 -17
- package/src/i18n/config.ts +8 -0
- package/src/i18n/repair-locale-casing.ts +51 -0
- package/src/search/query.ts +3 -2
- package/src/seed/apply.ts +9 -7
- package/src/seed/validate.ts +15 -4
- package/src/taxonomies/index.ts +64 -23
- package/dist/api-b8WIiGU4.mjs.map +0 -1
- package/dist/apply-CmIJK9j8.mjs.map +0 -1
- package/dist/bylines-BJbT4gKS.mjs.map +0 -1
- package/dist/config-CVssduLe.mjs.map +0 -1
- package/dist/dialect-helpers-HxEQGl_1.mjs.map +0 -1
- package/dist/index-wYnC6u4o.d.mts.map +0 -1
- package/dist/media-kIV1IxFf.mjs.map +0 -1
- package/dist/menus-BcyElFtI.mjs.map +0 -1
- package/dist/menus-CZyG6rvx.mjs.map +0 -1
- package/dist/redirects-BBq3n2Rj.mjs.map +0 -1
- package/dist/relations-BKvO39-9.mjs.map +0 -1
- package/dist/relations-Bh8jlFsU.d.mts.map +0 -1
- package/dist/search-Bff-7jFt.mjs.map +0 -1
- package/dist/secrets-CSwQIl4q.mjs.map +0 -1
- package/dist/taxonomies-Ce49uIzY.mjs.map +0 -1
- package/dist/taxonomies-DjSKBZpq.mjs.map +0 -1
- package/dist/validate-V9nCwq_-.mjs.map +0 -1
- package/dist/version-907opKac.mjs +0 -7
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"media-BjhhENaJ.mjs","names":[],"sources":["../src/database/repositories/media.ts"],"sourcesContent":["import { sql, type ExpressionBuilder, type Kysely, type SqlBool } from \"kysely\";\nimport { ulid } from \"ulidx\";\n\nimport type { Database, MediaRow } from \"../types.js\";\nimport type { FindManyResult } from \"./types.js\";\nimport { encodeCursor, decodeCursor } from \"./types.js\";\n\n/** Escape LIKE wildcard characters and the escape char itself in user-supplied values */\nfunction escapeLike(value: string): string {\n\treturn value.replaceAll(\"\\\\\", \"\\\\\\\\\").replaceAll(\"%\", \"\\\\%\").replaceAll(\"_\", \"\\\\_\");\n}\n\n/**\n * Normalize a mimeType filter (string or array) into a clean string[].\n * Entries that are empty strings are dropped.\n */\nfunction normalizeMimeFilter(input?: string | readonly string[]): string[] {\n\tif (!input) return [];\n\tconst arr = Array.isArray(input) ? input : [input];\n\treturn arr\n\t\t.filter((entry): entry is string => typeof entry === \"string\" && entry.length > 0)\n\t\t.map((entry) =>\n\t\t\tentry.endsWith(\"/\") ? entry.toLowerCase() : entry.split(\";\")[0].trim().toLowerCase(),\n\t\t);\n}\n\n/**\n * Build a WHERE clause that matches `mime_type` against any of the given\n * filter entries — exact equality for full MIMEs, LIKE prefix for entries\n * ending in \"/\".\n */\nfunction mimeMatchExpr(eb: ExpressionBuilder<Database, \"media\">, filters: string[]) {\n\treturn eb.or(\n\t\tfilters.map((entry) =>\n\t\t\tentry.endsWith(\"/\")\n\t\t\t\t? sql<SqlBool>`mime_type LIKE ${`${escapeLike(entry)}%`} ESCAPE '\\\\'`\n\t\t\t\t: eb(\"mime_type\", \"=\", entry),\n\t\t),\n\t);\n}\n\nexport type MediaStatus = \"pending\" | \"ready\" | \"failed\";\n\nexport interface MediaItem {\n\tid: string;\n\tfilename: string;\n\tmimeType: string;\n\tsize: number | null;\n\twidth: number | null;\n\theight: number | null;\n\talt: string | null;\n\tcaption: string | null;\n\tstorageKey: string;\n\tstatus: MediaStatus;\n\tcontentHash: string | null;\n\tblurhash: string | null;\n\tdominantColor: string | null;\n\tcreatedAt: string;\n\tauthorId: string | null;\n}\n\nexport interface CreateMediaInput {\n\tfilename: string;\n\tmimeType: string;\n\tsize?: number;\n\twidth?: number;\n\theight?: number;\n\talt?: string;\n\tcaption?: string;\n\tstorageKey: string;\n\tcontentHash?: string;\n\tblurhash?: string;\n\tdominantColor?: string;\n\tstatus?: MediaStatus;\n\tauthorId?: string;\n}\n\nexport interface FindManyMediaOptions {\n\tlimit?: number;\n\tcursor?: string;\n\t/** Filter by MIME type. Pass a string for a single prefix/exact, or an array to match any. Strings ending with \"/\" are treated as LIKE prefix matches; others are exact equality. */\n\tmimeType?: string | readonly string[];\n\tstatus?: MediaStatus | \"all\"; // Filter by status, defaults to \"ready\"\n\t/** Case-insensitive substring matched against the filename (covers filename and extension). */\n\tq?: string;\n}\n\n/**\n * Media repository for database operations\n */\nexport class MediaRepository {\n\tconstructor(private db: Kysely<Database>) {}\n\n\t/**\n\t * Create a new media item\n\t */\n\tasync create(input: CreateMediaInput): Promise<MediaItem> {\n\t\tconst id = ulid();\n\t\tconst now = new Date().toISOString();\n\n\t\tconst row: Omit<MediaRow, \"rowid\"> = {\n\t\t\tid,\n\t\t\tfilename: input.filename,\n\t\t\tmime_type: input.mimeType,\n\t\t\tsize: input.size ?? null,\n\t\t\twidth: input.width ?? null,\n\t\t\theight: input.height ?? null,\n\t\t\talt: input.alt ?? null,\n\t\t\tcaption: input.caption ?? null,\n\t\t\tstorage_key: input.storageKey,\n\t\t\tcontent_hash: input.contentHash ?? null,\n\t\t\tblurhash: input.blurhash ?? null,\n\t\t\tdominant_color: input.dominantColor ?? null,\n\t\t\tstatus: input.status ?? \"ready\",\n\t\t\tcreated_at: now,\n\t\t\tauthor_id: input.authorId ?? null,\n\t\t};\n\n\t\tawait this.db.insertInto(\"media\").values(row).execute();\n\n\t\treturn this.rowToItem(row);\n\t}\n\n\t/**\n\t * Create a pending media item (for signed URL upload flow)\n\t */\n\tasync createPending(input: {\n\t\tfilename: string;\n\t\tmimeType: string;\n\t\tsize?: number;\n\t\tstorageKey: string;\n\t\tcontentHash?: string;\n\t\tauthorId?: string;\n\t}): Promise<MediaItem> {\n\t\treturn this.create({\n\t\t\t...input,\n\t\t\tstatus: \"pending\",\n\t\t});\n\t}\n\n\t/**\n\t * Confirm upload (mark as ready)\n\t */\n\tasync confirmUpload(\n\t\tid: string,\n\t\tmetadata?: {\n\t\t\twidth?: number;\n\t\t\theight?: number;\n\t\t\tsize?: number;\n\t\t\tblurhash?: string;\n\t\t\tdominantColor?: string;\n\t\t},\n\t): Promise<MediaItem | null> {\n\t\tconst existing = await this.findById(id);\n\t\tif (!existing) {\n\t\t\treturn null;\n\t\t}\n\n\t\tconst updates: Partial<MediaRow> = {\n\t\t\tstatus: \"ready\",\n\t\t};\n\t\tif (metadata?.width !== undefined) updates.width = metadata.width;\n\t\tif (metadata?.height !== undefined) updates.height = metadata.height;\n\t\tif (metadata?.size !== undefined) updates.size = metadata.size;\n\t\tif (metadata?.blurhash !== undefined) updates.blurhash = metadata.blurhash;\n\t\tif (metadata?.dominantColor !== undefined) updates.dominant_color = metadata.dominantColor;\n\n\t\tawait this.db.updateTable(\"media\").set(updates).where(\"id\", \"=\", id).execute();\n\n\t\treturn this.findById(id);\n\t}\n\n\t/**\n\t * Mark upload as failed\n\t */\n\tasync markFailed(id: string): Promise<MediaItem | null> {\n\t\tconst existing = await this.findById(id);\n\t\tif (!existing) {\n\t\t\treturn null;\n\t\t}\n\n\t\tawait this.db.updateTable(\"media\").set({ status: \"failed\" }).where(\"id\", \"=\", id).execute();\n\n\t\treturn this.findById(id);\n\t}\n\n\t/**\n\t * Find media by ID\n\t */\n\tasync findById(id: string): Promise<MediaItem | null> {\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"media\")\n\t\t\t.selectAll()\n\t\t\t.where(\"id\", \"=\", id)\n\t\t\t.executeTakeFirst();\n\n\t\treturn row ? this.rowToItem(row) : null;\n\t}\n\n\t/**\n\t * Find media by filename\n\t * Useful for idempotent imports\n\t */\n\tasync findByFilename(filename: string): Promise<MediaItem | null> {\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"media\")\n\t\t\t.selectAll()\n\t\t\t.where(\"filename\", \"=\", filename)\n\t\t\t.executeTakeFirst();\n\n\t\treturn row ? this.rowToItem(row) : null;\n\t}\n\n\t/**\n\t * Find media by content hash\n\t * Used for deduplication - same content = same hash\n\t */\n\tasync findByContentHash(contentHash: string): Promise<MediaItem | null> {\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"media\")\n\t\t\t.selectAll()\n\t\t\t.where(\"content_hash\", \"=\", contentHash)\n\t\t\t.where(\"status\", \"=\", \"ready\")\n\t\t\t.executeTakeFirst();\n\n\t\treturn row ? this.rowToItem(row) : null;\n\t}\n\n\t/**\n\t * Find many media items with cursor pagination\n\t *\n\t * Uses keyset pagination (cursor-based) for consistent results.\n\t * The cursor encodes the created_at and id of the last item.\n\t */\n\tasync findMany(options: FindManyMediaOptions = {}): Promise<FindManyResult<MediaItem>> {\n\t\tconst limit = Math.min(options.limit || 50, 100);\n\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"media\")\n\t\t\t.selectAll()\n\t\t\t.orderBy(\"created_at\", \"desc\")\n\t\t\t.orderBy(\"id\", \"desc\")\n\t\t\t.limit(limit + 1);\n\n\t\t// Handle cursor-based pagination — throws on invalid cursor.\n\t\tif (options.cursor) {\n\t\t\tconst { orderValue: createdAt, id: cursorId } = decodeCursor(options.cursor);\n\n\t\t\t// Keyset pagination: get items where (created_at, id) < cursor\n\t\t\tquery = query.where((eb) =>\n\t\t\t\teb.or([\n\t\t\t\t\teb(\"created_at\", \"<\", createdAt),\n\t\t\t\t\teb.and([eb(\"created_at\", \"=\", createdAt), eb(\"id\", \"<\", cursorId)]),\n\t\t\t\t]),\n\t\t\t);\n\t\t}\n\n\t\tconst mimeFilters = normalizeMimeFilter(options.mimeType);\n\t\tif (mimeFilters.length > 0) {\n\t\t\tquery = query.where((eb) => mimeMatchExpr(eb, mimeFilters));\n\t\t}\n\n\t\t// Case-insensitive filename substring search (also matches extensions).\n\t\t// LIKE wildcards in the term are escaped so they're treated literally.\n\t\tconst term = options.q?.trim();\n\t\tif (term) {\n\t\t\tconst pattern = `%${escapeLike(term)}%`;\n\t\t\tquery = query.where(\n\t\t\t\tsql<string>`lower(filename)`,\n\t\t\t\t\"like\",\n\t\t\t\tsql<string>`lower(${pattern}) escape '\\\\'`,\n\t\t\t);\n\t\t}\n\n\t\t// Default to only showing ready items\n\t\tif (options.status !== \"all\") {\n\t\t\tquery = query.where(\"status\", \"=\", options.status ?? \"ready\");\n\t\t}\n\n\t\tconst rows = await query.execute();\n\n\t\tconst hasMore = rows.length > limit;\n\t\tconst items = rows.slice(0, limit).map((row) => this.rowToItem(row));\n\n\t\tlet nextCursor: string | undefined;\n\t\tif (hasMore && items.length > 0) {\n\t\t\tconst lastItem = items.at(-1)!;\n\t\t\tnextCursor = encodeCursor(lastItem.createdAt, lastItem.id);\n\t\t}\n\n\t\treturn { items, nextCursor };\n\t}\n\n\t/**\n\t * Update media metadata\n\t */\n\tasync update(\n\t\tid: string,\n\t\tinput: Partial<Pick<CreateMediaInput, \"alt\" | \"caption\" | \"width\" | \"height\">>,\n\t): Promise<MediaItem | null> {\n\t\tconst existing = await this.findById(id);\n\t\tif (!existing) {\n\t\t\treturn null;\n\t\t}\n\n\t\tconst updates: Partial<MediaRow> = {};\n\t\tif (input.alt !== undefined) updates.alt = input.alt;\n\t\tif (input.caption !== undefined) updates.caption = input.caption;\n\t\tif (input.width !== undefined) updates.width = input.width;\n\t\tif (input.height !== undefined) updates.height = input.height;\n\n\t\tif (Object.keys(updates).length > 0) {\n\t\t\tawait this.db.updateTable(\"media\").set(updates).where(\"id\", \"=\", id).execute();\n\t\t}\n\n\t\treturn this.findById(id);\n\t}\n\n\t/**\n\t * Delete media item\n\t */\n\tasync delete(id: string): Promise<boolean> {\n\t\tconst result = await this.db.deleteFrom(\"media\").where(\"id\", \"=\", id).executeTakeFirst();\n\n\t\treturn (result.numDeletedRows ?? 0) > 0;\n\t}\n\n\t/**\n\t * Count media items\n\t */\n\tasync count(mimeType?: string | readonly string[]): Promise<number> {\n\t\tconst filters = normalizeMimeFilter(mimeType);\n\t\tlet query = this.db.selectFrom(\"media\").select((eb) => eb.fn.count<number>(\"id\").as(\"count\"));\n\n\t\tif (filters.length > 0) {\n\t\t\tquery = query.where((eb) => mimeMatchExpr(eb, filters));\n\t\t}\n\n\t\tconst result = await query.executeTakeFirst();\n\t\treturn Number(result?.count || 0);\n\t}\n\n\t/**\n\t * Delete pending uploads older than the given age.\n\t * Pending uploads that were never confirmed indicate abandoned upload flows.\n\t *\n\t * Returns the storage keys of deleted rows so callers can remove the\n\t * corresponding files from object storage.\n\t */\n\tasync cleanupPendingUploads(maxAgeMs: number = 60 * 60 * 1000): Promise<string[]> {\n\t\tconst cutoff = new Date(Date.now() - maxAgeMs).toISOString();\n\n\t\t// Select the storage keys first -- SQLite doesn't support RETURNING\n\t\t// on DELETE in all drivers, and Kysely's RETURNING isn't universal.\n\t\tconst rows = await this.db\n\t\t\t.selectFrom(\"media\")\n\t\t\t.select(\"storage_key\")\n\t\t\t.where(\"status\", \"=\", \"pending\")\n\t\t\t.where(\"created_at\", \"<\", cutoff)\n\t\t\t.execute();\n\n\t\tif (rows.length === 0) return [];\n\n\t\tawait this.db\n\t\t\t.deleteFrom(\"media\")\n\t\t\t.where(\"status\", \"=\", \"pending\")\n\t\t\t.where(\"created_at\", \"<\", cutoff)\n\t\t\t.execute();\n\n\t\treturn rows.map((r) => r.storage_key);\n\t}\n\n\t/**\n\t * Convert database row to MediaItem\n\t */\n\tprivate rowToItem(row: MediaRow): MediaItem {\n\t\treturn {\n\t\t\tid: row.id,\n\t\t\tfilename: row.filename,\n\t\t\tmimeType: row.mime_type,\n\t\t\tsize: row.size,\n\t\t\twidth: row.width,\n\t\t\theight: row.height,\n\t\t\talt: row.alt,\n\t\t\tcaption: row.caption,\n\t\t\tstorageKey: row.storage_key,\n\t\t\tcontentHash: row.content_hash,\n\t\t\tblurhash: row.blurhash,\n\t\t\tdominantColor: row.dominant_color,\n\t\t\t// eslint-disable-next-line typescript/no-unsafe-type-assertion -- DB stores string; validated at insert but linter can't follow\n\t\t\tstatus: row.status as MediaStatus,\n\t\t\tcreatedAt: row.created_at,\n\t\t\tauthorId: row.author_id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AG,SAAS,CAAC,aAAa;EAI5D,MAAM,OAAO,MAAM,KAAK,GACtB,WAAW,QAAQ,CACnB,OAAO,cAAc,CACrB,MAAM,UAAU,KAAK,UAAU,CAC/B,MAAM,cAAc,KAAK,OAAO,CAChC,SAAS;AAEX,MAAI,KAAK,WAAW,EAAG,QAAO,EAAE;AAEhC,QAAM,KAAK,GACT,WAAW,QAAQ,CACnB,MAAM,UAAU,KAAK,UAAU,CAC/B,MAAM,cAAc,KAAK,OAAO,CAChC,SAAS;AAEX,SAAO,KAAK,KAAK,MAAM,EAAE,YAAY;;;;;CAMtC,AAAQ,UAAU,KAA0B;AAC3C,SAAO;GACN,IAAI,IAAI;GACR,UAAU,IAAI;GACd,UAAU,IAAI;GACd,MAAM,IAAI;GACV,OAAO,IAAI;GACX,QAAQ,IAAI;GACZ,KAAK,IAAI;GACT,SAAS,IAAI;GACb,YAAY,IAAI;GAChB,aAAa,IAAI;GACjB,UAAU,IAAI;GACd,eAAe,IAAI;GAEnB,QAAQ,IAAI;GACZ,WAAW,IAAI;GACf,UAAU,IAAI;GACd"}
|
|
1
|
+
{"version":3,"file":"media-its1WLYv.mjs","names":[],"sources":["../src/database/repositories/media.ts"],"sourcesContent":["import { sql, type ExpressionBuilder, type Kysely, type SqlBool } from \"kysely\";\nimport { ulid } from \"ulidx\";\n\nimport type { Database, MediaRow } from \"../types.js\";\nimport type { FindManyResult } from \"./types.js\";\nimport { encodeCursor, decodeCursor } from \"./types.js\";\n\n/** Escape LIKE wildcard characters and the escape char itself in user-supplied values */\nfunction escapeLike(value: string): string {\n\treturn value.replaceAll(\"\\\\\", \"\\\\\\\\\").replaceAll(\"%\", \"\\\\%\").replaceAll(\"_\", \"\\\\_\");\n}\n\n/**\n * Normalize a mimeType filter (string or array) into a clean string[].\n * Entries that are empty strings are dropped.\n */\nfunction normalizeMimeFilter(input?: string | readonly string[]): string[] {\n\tif (!input) return [];\n\tconst arr = Array.isArray(input) ? input : [input];\n\treturn arr\n\t\t.filter((entry): entry is string => typeof entry === \"string\" && entry.length > 0)\n\t\t.map((entry) =>\n\t\t\tentry.endsWith(\"/\") ? entry.toLowerCase() : entry.split(\";\")[0].trim().toLowerCase(),\n\t\t);\n}\n\n/**\n * Build a WHERE clause that matches `mime_type` against any of the given\n * filter entries — exact equality for full MIMEs, LIKE prefix for entries\n * ending in \"/\".\n */\nfunction mimeMatchExpr(eb: ExpressionBuilder<Database, \"media\">, filters: string[]) {\n\treturn eb.or(\n\t\tfilters.map((entry) =>\n\t\t\tentry.endsWith(\"/\")\n\t\t\t\t? sql<SqlBool>`mime_type LIKE ${`${escapeLike(entry)}%`} ESCAPE '\\\\'`\n\t\t\t\t: eb(\"mime_type\", \"=\", entry),\n\t\t),\n\t);\n}\n\nexport type MediaStatus = \"pending\" | \"ready\" | \"failed\";\n\nexport interface MediaItem {\n\tid: string;\n\tfilename: string;\n\tmimeType: string;\n\tsize: number | null;\n\twidth: number | null;\n\theight: number | null;\n\talt: string | null;\n\tcaption: string | null;\n\tstorageKey: string;\n\tstatus: MediaStatus;\n\tcontentHash: string | null;\n\tblurhash: string | null;\n\tdominantColor: string | null;\n\tcreatedAt: string;\n\tauthorId: string | null;\n}\n\nexport interface CreateMediaInput {\n\tfilename: string;\n\tmimeType: string;\n\tsize?: number;\n\twidth?: number;\n\theight?: number;\n\talt?: string;\n\tcaption?: string;\n\tstorageKey: string;\n\tcontentHash?: string;\n\tblurhash?: string;\n\tdominantColor?: string;\n\tstatus?: MediaStatus;\n\tauthorId?: string;\n}\n\nexport interface FindManyMediaOptions {\n\tlimit?: number;\n\tcursor?: string;\n\t/** Filter by MIME type. Pass a string for a single prefix/exact, or an array to match any. Strings ending with \"/\" are treated as LIKE prefix matches; others are exact equality. */\n\tmimeType?: string | readonly string[];\n\tstatus?: MediaStatus | \"all\"; // Filter by status, defaults to \"ready\"\n\t/** Case-insensitive substring matched against the filename (covers filename and extension). */\n\tq?: string;\n}\n\n/**\n * Media repository for database operations\n */\nexport class MediaRepository {\n\tconstructor(private db: Kysely<Database>) {}\n\n\t/**\n\t * Create a new media item\n\t */\n\tasync create(input: CreateMediaInput): Promise<MediaItem> {\n\t\tconst id = ulid();\n\t\tconst now = new Date().toISOString();\n\n\t\tconst row: Omit<MediaRow, \"rowid\"> = {\n\t\t\tid,\n\t\t\tfilename: input.filename,\n\t\t\tmime_type: input.mimeType,\n\t\t\tsize: input.size ?? null,\n\t\t\twidth: input.width ?? null,\n\t\t\theight: input.height ?? null,\n\t\t\talt: input.alt ?? null,\n\t\t\tcaption: input.caption ?? null,\n\t\t\tstorage_key: input.storageKey,\n\t\t\tcontent_hash: input.contentHash ?? null,\n\t\t\tblurhash: input.blurhash ?? null,\n\t\t\tdominant_color: input.dominantColor ?? null,\n\t\t\tstatus: input.status ?? \"ready\",\n\t\t\tcreated_at: now,\n\t\t\tauthor_id: input.authorId ?? null,\n\t\t};\n\n\t\tawait this.db.insertInto(\"media\").values(row).execute();\n\n\t\treturn this.rowToItem(row);\n\t}\n\n\t/**\n\t * Create a pending media item (for signed URL upload flow)\n\t */\n\tasync createPending(input: {\n\t\tfilename: string;\n\t\tmimeType: string;\n\t\tsize?: number;\n\t\tstorageKey: string;\n\t\tcontentHash?: string;\n\t\tauthorId?: string;\n\t}): Promise<MediaItem> {\n\t\treturn this.create({\n\t\t\t...input,\n\t\t\tstatus: \"pending\",\n\t\t});\n\t}\n\n\t/**\n\t * Confirm upload (mark as ready)\n\t */\n\tasync confirmUpload(\n\t\tid: string,\n\t\tmetadata?: {\n\t\t\twidth?: number;\n\t\t\theight?: number;\n\t\t\tsize?: number;\n\t\t\tblurhash?: string;\n\t\t\tdominantColor?: string;\n\t\t},\n\t): Promise<MediaItem | null> {\n\t\tconst existing = await this.findById(id);\n\t\tif (!existing) {\n\t\t\treturn null;\n\t\t}\n\n\t\tconst updates: Partial<MediaRow> = {\n\t\t\tstatus: \"ready\",\n\t\t};\n\t\tif (metadata?.width !== undefined) updates.width = metadata.width;\n\t\tif (metadata?.height !== undefined) updates.height = metadata.height;\n\t\tif (metadata?.size !== undefined) updates.size = metadata.size;\n\t\tif (metadata?.blurhash !== undefined) updates.blurhash = metadata.blurhash;\n\t\tif (metadata?.dominantColor !== undefined) updates.dominant_color = metadata.dominantColor;\n\n\t\tawait this.db.updateTable(\"media\").set(updates).where(\"id\", \"=\", id).execute();\n\n\t\treturn this.findById(id);\n\t}\n\n\t/**\n\t * Mark upload as failed\n\t */\n\tasync markFailed(id: string): Promise<MediaItem | null> {\n\t\tconst existing = await this.findById(id);\n\t\tif (!existing) {\n\t\t\treturn null;\n\t\t}\n\n\t\tawait this.db.updateTable(\"media\").set({ status: \"failed\" }).where(\"id\", \"=\", id).execute();\n\n\t\treturn this.findById(id);\n\t}\n\n\t/**\n\t * Find media by ID\n\t */\n\tasync findById(id: string): Promise<MediaItem | null> {\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"media\")\n\t\t\t.selectAll()\n\t\t\t.where(\"id\", \"=\", id)\n\t\t\t.executeTakeFirst();\n\n\t\treturn row ? this.rowToItem(row) : null;\n\t}\n\n\t/**\n\t * Find media by filename\n\t * Useful for idempotent imports\n\t */\n\tasync findByFilename(filename: string): Promise<MediaItem | null> {\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"media\")\n\t\t\t.selectAll()\n\t\t\t.where(\"filename\", \"=\", filename)\n\t\t\t.executeTakeFirst();\n\n\t\treturn row ? this.rowToItem(row) : null;\n\t}\n\n\t/**\n\t * Find media by content hash\n\t * Used for deduplication - same content = same hash\n\t */\n\tasync findByContentHash(contentHash: string): Promise<MediaItem | null> {\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"media\")\n\t\t\t.selectAll()\n\t\t\t.where(\"content_hash\", \"=\", contentHash)\n\t\t\t.where(\"status\", \"=\", \"ready\")\n\t\t\t.executeTakeFirst();\n\n\t\treturn row ? this.rowToItem(row) : null;\n\t}\n\n\t/**\n\t * Find many media items with cursor pagination\n\t *\n\t * Uses keyset pagination (cursor-based) for consistent results.\n\t * The cursor encodes the created_at and id of the last item.\n\t */\n\tasync findMany(options: FindManyMediaOptions = {}): Promise<FindManyResult<MediaItem>> {\n\t\tconst limit = Math.min(options.limit || 50, 100);\n\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"media\")\n\t\t\t.selectAll()\n\t\t\t.orderBy(\"created_at\", \"desc\")\n\t\t\t.orderBy(\"id\", \"desc\")\n\t\t\t.limit(limit + 1);\n\n\t\t// Handle cursor-based pagination — throws on invalid cursor.\n\t\tif (options.cursor) {\n\t\t\tconst { orderValue: createdAt, id: cursorId } = decodeCursor(options.cursor);\n\n\t\t\t// Keyset pagination: get items where (created_at, id) < cursor\n\t\t\tquery = query.where((eb) =>\n\t\t\t\teb.or([\n\t\t\t\t\teb(\"created_at\", \"<\", createdAt),\n\t\t\t\t\teb.and([eb(\"created_at\", \"=\", createdAt), eb(\"id\", \"<\", cursorId)]),\n\t\t\t\t]),\n\t\t\t);\n\t\t}\n\n\t\tconst mimeFilters = normalizeMimeFilter(options.mimeType);\n\t\tif (mimeFilters.length > 0) {\n\t\t\tquery = query.where((eb) => mimeMatchExpr(eb, mimeFilters));\n\t\t}\n\n\t\t// Case-insensitive filename substring search (also matches extensions).\n\t\t// LIKE wildcards in the term are escaped so they're treated literally.\n\t\tconst term = options.q?.trim();\n\t\tif (term) {\n\t\t\tconst pattern = `%${escapeLike(term)}%`;\n\t\t\tquery = query.where(\n\t\t\t\tsql<string>`lower(filename)`,\n\t\t\t\t\"like\",\n\t\t\t\tsql<string>`lower(${pattern}) escape '\\\\'`,\n\t\t\t);\n\t\t}\n\n\t\t// Default to only showing ready items\n\t\tif (options.status !== \"all\") {\n\t\t\tquery = query.where(\"status\", \"=\", options.status ?? \"ready\");\n\t\t}\n\n\t\tconst rows = await query.execute();\n\n\t\tconst hasMore = rows.length > limit;\n\t\tconst items = rows.slice(0, limit).map((row) => this.rowToItem(row));\n\n\t\tlet nextCursor: string | undefined;\n\t\tif (hasMore && items.length > 0) {\n\t\t\tconst lastItem = items.at(-1)!;\n\t\t\tnextCursor = encodeCursor(lastItem.createdAt, lastItem.id);\n\t\t}\n\n\t\treturn { items, nextCursor };\n\t}\n\n\t/**\n\t * Update media metadata\n\t */\n\tasync update(\n\t\tid: string,\n\t\tinput: Partial<Pick<CreateMediaInput, \"alt\" | \"caption\" | \"width\" | \"height\">>,\n\t): Promise<MediaItem | null> {\n\t\tconst existing = await this.findById(id);\n\t\tif (!existing) {\n\t\t\treturn null;\n\t\t}\n\n\t\tconst updates: Partial<MediaRow> = {};\n\t\tif (input.alt !== undefined) updates.alt = input.alt;\n\t\tif (input.caption !== undefined) updates.caption = input.caption;\n\t\tif (input.width !== undefined) updates.width = input.width;\n\t\tif (input.height !== undefined) updates.height = input.height;\n\n\t\tif (Object.keys(updates).length > 0) {\n\t\t\tawait this.db.updateTable(\"media\").set(updates).where(\"id\", \"=\", id).execute();\n\t\t}\n\n\t\treturn this.findById(id);\n\t}\n\n\t/**\n\t * Delete media item\n\t */\n\tasync delete(id: string): Promise<boolean> {\n\t\tconst result = await this.db.deleteFrom(\"media\").where(\"id\", \"=\", id).executeTakeFirst();\n\n\t\treturn (result.numDeletedRows ?? 0) > 0;\n\t}\n\n\t/**\n\t * Count media items\n\t */\n\tasync count(mimeType?: string | readonly string[]): Promise<number> {\n\t\tconst filters = normalizeMimeFilter(mimeType);\n\t\tlet query = this.db.selectFrom(\"media\").select((eb) => eb.fn.count<number>(\"id\").as(\"count\"));\n\n\t\tif (filters.length > 0) {\n\t\t\tquery = query.where((eb) => mimeMatchExpr(eb, filters));\n\t\t}\n\n\t\tconst result = await query.executeTakeFirst();\n\t\treturn Number(result?.count || 0);\n\t}\n\n\t/**\n\t * Delete pending uploads older than the given age.\n\t * Pending uploads that were never confirmed indicate abandoned upload flows.\n\t *\n\t * Returns the storage keys of deleted rows so callers can remove the\n\t * corresponding files from object storage.\n\t */\n\tasync cleanupPendingUploads(maxAgeMs: number = 60 * 60 * 1000): Promise<string[]> {\n\t\tconst cutoff = new Date(Date.now() - maxAgeMs).toISOString();\n\n\t\t// Select the storage keys first -- SQLite doesn't support RETURNING\n\t\t// on DELETE in all drivers, and Kysely's RETURNING isn't universal.\n\t\tconst rows = await this.db\n\t\t\t.selectFrom(\"media\")\n\t\t\t.select(\"storage_key\")\n\t\t\t.where(\"status\", \"=\", \"pending\")\n\t\t\t.where(\"created_at\", \"<\", cutoff)\n\t\t\t.execute();\n\n\t\tif (rows.length === 0) return [];\n\n\t\tawait this.db\n\t\t\t.deleteFrom(\"media\")\n\t\t\t.where(\"status\", \"=\", \"pending\")\n\t\t\t.where(\"created_at\", \"<\", cutoff)\n\t\t\t.execute();\n\n\t\treturn rows.map((r) => r.storage_key);\n\t}\n\n\t/**\n\t * Convert database row to MediaItem\n\t */\n\tprivate rowToItem(row: MediaRow): MediaItem {\n\t\treturn {\n\t\t\tid: row.id,\n\t\t\tfilename: row.filename,\n\t\t\tmimeType: row.mime_type,\n\t\t\tsize: row.size,\n\t\t\twidth: row.width,\n\t\t\theight: row.height,\n\t\t\talt: row.alt,\n\t\t\tcaption: row.caption,\n\t\t\tstorageKey: row.storage_key,\n\t\t\tcontentHash: row.content_hash,\n\t\t\tblurhash: row.blurhash,\n\t\t\tdominantColor: row.dominant_color,\n\t\t\t// eslint-disable-next-line typescript/no-unsafe-type-assertion -- DB stores string; validated at insert but linter can't follow\n\t\t\tstatus: row.status as MediaStatus,\n\t\t\tcreatedAt: row.created_at,\n\t\t\tauthorId: row.author_id,\n\t\t};\n\t}\n}\n"],"mappings":";;;;;;AAQA,SAAS,WAAW,OAAuB;AAC1C,QAAO,MAAM,WAAW,MAAM,OAAO,CAAC,WAAW,KAAK,MAAM,CAAC,WAAW,KAAK,MAAM;;;;;;AAOpF,SAAS,oBAAoB,OAA8C;AAC1E,KAAI,CAAC,MAAO,QAAO,EAAE;AAErB,SADY,MAAM,QAAQ,MAAM,GAAG,QAAQ,CAAC,MAAM,EAEhD,QAAQ,UAA2B,OAAO,UAAU,YAAY,MAAM,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,SAAO,KAAK,KAAK,MAAM,EAAE,YAAY;;;;;CAMtC,AAAQ,UAAU,KAA0B;AAC3C,SAAO;GACN,IAAI,IAAI;GACR,UAAU,IAAI;GACd,UAAU,IAAI;GACd,MAAM,IAAI;GACV,OAAO,IAAI;GACX,QAAQ,IAAI;GACZ,KAAK,IAAI;GACT,SAAS,IAAI;GACb,YAAY,IAAI;GAChB,aAAa,IAAI;GACjB,UAAU,IAAI;GACd,eAAe,IAAI;GAEnB,QAAQ,IAAI;GACZ,WAAW,IAAI;GACf,UAAU,IAAI;GACd"}
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { n as decodeBase64Bytes } from "./base64-B-PsqheR.mjs";
|
|
2
|
-
import "./types-
|
|
3
|
-
import { t as MediaRepository } from "./media-
|
|
2
|
+
import "./types-CrRUFdej.mjs";
|
|
3
|
+
import { t as MediaRepository } from "./media-its1WLYv.mjs";
|
|
4
4
|
import { n as normalizeMime, t as matchesMimeAllowlist } from "./mime-DfIVjNkr.mjs";
|
|
5
5
|
import { t as enrichImageMetadata } from "./enrich-CFJJgxs_.mjs";
|
|
6
6
|
import { t as computeContentHash } from "./hash-DFFrkivP.mjs";
|
|
7
7
|
import { r as ssrfSafeFetch, t as SsrfError } from "./ssrf-CviKqWmq.mjs";
|
|
8
|
-
import { n as DEFAULT_MAX_UPLOAD_SIZE, r as formatFileSize, t as CONTENT_TYPE_RE } from "./media-
|
|
8
|
+
import { n as DEFAULT_MAX_UPLOAD_SIZE, r as formatFileSize, t as CONTENT_TYPE_RE } from "./media-BJ6SRY3g.mjs";
|
|
9
9
|
import { t as GLOBAL_UPLOAD_ALLOWLIST } from "./media-allowlist-jUppPWFy.mjs";
|
|
10
10
|
import { ulid } from "ulidx";
|
|
11
11
|
import * as path from "node:path";
|
|
@@ -142,4 +142,4 @@ async function handleMediaUpload(db, storage, input) {
|
|
|
142
142
|
|
|
143
143
|
//#endregion
|
|
144
144
|
export { handleMediaUpload };
|
|
145
|
-
//# sourceMappingURL=media-upload-
|
|
145
|
+
//# sourceMappingURL=media-upload-DNu3QySc.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"media-upload-D2wk3EIt.mjs","names":[],"sources":["../src/api/handlers/media-upload.ts"],"sourcesContent":["/**\n * Programmatic media upload handler (MCP `media_upload` tool).\n *\n * Accepts file bytes as base64 or fetches them from an external URL\n * (SSRF-guarded), then runs the same pipeline as the multipart REST\n * upload route: allowlist + size validation, content-hash deduplication,\n * storage upload, image metadata enrichment, and record creation.\n */\n\nimport * as path from \"node:path\";\n\nimport type { Kysely } from \"kysely\";\nimport { ulid } from \"ulidx\";\n\nimport { MediaRepository, type MediaItem } from \"../../database/repositories/media.js\";\nimport type { Database } from \"../../database/types.js\";\nimport { enrichImageMetadata } from \"../../media/enrich.js\";\nimport { matchesMimeAllowlist, normalizeMime } from \"../../media/mime.js\";\nimport { SsrfError, ssrfSafeFetch } from \"../../security/ssrf.js\";\nimport type { Storage } from \"../../storage/types.js\";\nimport { decodeBase64Bytes } from \"../../utils/base64.js\";\nimport { computeContentHash } from \"../../utils/hash.js\";\nimport { CONTENT_TYPE_RE, DEFAULT_MAX_UPLOAD_SIZE, formatFileSize } from \"../schemas/media.js\";\nimport type { ApiResult } from \"../types.js\";\nimport { GLOBAL_UPLOAD_ALLOWLIST } from \"./media-allowlist.js\";\n\nexport interface MediaUploadInput {\n\t/** Original filename (e.g. 'logo.png'); the extension is kept on the storage key. */\n\tfilename: string;\n\t/** Base64-encoded file contents. Exactly one of `base64` / `url` must be set. */\n\tbase64?: string;\n\t/** External http(s) URL to fetch the file from. Exactly one of `base64` / `url` must be set. */\n\turl?: string;\n\t/**\n\t * MIME type. Required with `base64`; optional with `url` (falls back to\n\t * the response's Content-Type header).\n\t */\n\tcontentType?: string;\n\t/** Alt text stored on the media record. */\n\talt?: string;\n\tauthorId?: string;\n\t/** Upload size limit in bytes (defaults to DEFAULT_MAX_UPLOAD_SIZE). */\n\tmaxUploadSize?: number;\n}\n\nexport type MediaUploadResult = ApiResult<{\n\titem: MediaItem & { url: string };\n\tdeduplicated?: boolean;\n}>;\n\nfunction fail(code: string, message: string): MediaUploadResult {\n\treturn { success: false, error: { code, message } };\n}\n\n/** Same relative-URL shape the REST media routes return. */\nfunction withUrl(item: MediaItem): MediaItem & { url: string } {\n\treturn { ...item, url: `/_emdash/api/media/file/${item.storageKey}` };\n}\n\n/** Strip parameters from a Content-Type header value (e.g. '; charset=...'). */\nfunction bareMime(headerValue: string): string {\n\treturn (headerValue.split(\";\")[0] ?? \"\").trim();\n}\n\n/**\n * Acquire the file bytes and MIME type from either the base64 payload or\n * the external URL. Returns an error result on any validation failure.\n */\nasync function acquireBytes(\n\tinput: MediaUploadInput,\n\tmaxUploadSize: number,\n): Promise<{ bytes: Uint8Array; mimeType: string } | MediaUploadResult> {\n\tif (input.base64) {\n\t\tif (!input.contentType) {\n\t\t\treturn fail(\"VALIDATION_ERROR\", \"contentType is required when uploading base64 data\");\n\t\t}\n\t\t// Cheap size precheck on the encoded string (decoded size is ~3/4 of\n\t\t// the base64 length) before allocating the decoded buffer.\n\t\tif ((input.base64.length * 3) / 4 > maxUploadSize) {\n\t\t\treturn fail(\n\t\t\t\t\"PAYLOAD_TOO_LARGE\",\n\t\t\t\t`File exceeds maximum size of ${formatFileSize(maxUploadSize)}`,\n\t\t\t);\n\t\t}\n\t\ttry {\n\t\t\treturn { bytes: decodeBase64Bytes(input.base64), mimeType: input.contentType };\n\t\t} catch {\n\t\t\treturn fail(\"VALIDATION_ERROR\", \"Invalid base64 data\");\n\t\t}\n\t}\n\n\t// url mode — the caller guarantees exactly one source, so url is set here\n\tconst url = input.url;\n\tif (!url) {\n\t\treturn fail(\"VALIDATION_ERROR\", \"Provide exactly one of 'base64' or 'url'\");\n\t}\n\tlet response: Response;\n\ttry {\n\t\tresponse = await ssrfSafeFetch(url, { headers: { accept: \"*/*\" } });\n\t} catch (error) {\n\t\tif (error instanceof SsrfError) {\n\t\t\treturn fail(\"VALIDATION_ERROR\", `URL not allowed: ${error.message}`);\n\t\t}\n\t\treturn fail(\"FETCH_ERROR\", \"Failed to fetch file from URL\");\n\t}\n\tif (!response.ok) {\n\t\treturn fail(\"FETCH_ERROR\", `Failed to fetch file from URL (HTTP ${response.status})`);\n\t}\n\n\tconst contentLength = response.headers.get(\"Content-Length\");\n\tif (contentLength && parseInt(contentLength, 10) > maxUploadSize) {\n\t\treturn fail(\n\t\t\t\"PAYLOAD_TOO_LARGE\",\n\t\t\t`File exceeds maximum size of ${formatFileSize(maxUploadSize)}`,\n\t\t);\n\t}\n\n\tconst mimeType = input.contentType ?? bareMime(response.headers.get(\"Content-Type\") ?? \"\");\n\tif (!mimeType) {\n\t\treturn fail(\"VALIDATION_ERROR\", \"Could not determine MIME type — pass contentType explicitly\");\n\t}\n\n\tconst bytes = new Uint8Array(await response.arrayBuffer());\n\treturn { bytes, mimeType };\n}\n\n/**\n * Upload a media file from base64 data or an external URL.\n *\n * Mirrors the REST `POST /_emdash/api/media` route: global MIME allowlist,\n * size limit, content-hash dedupe (returns the existing item with\n * `deduplicated: true`), storage upload with cleanup on failure, and\n * image metadata enrichment (dimensions, blurhash, dominant color).\n */\nexport async function handleMediaUpload(\n\tdb: Kysely<Database>,\n\tstorage: Storage,\n\tinput: MediaUploadInput,\n): Promise<MediaUploadResult> {\n\tif (!input.base64 === !input.url) {\n\t\treturn fail(\"VALIDATION_ERROR\", \"Provide exactly one of 'base64' or 'url'\");\n\t}\n\n\tconst rawMax = input.maxUploadSize ?? DEFAULT_MAX_UPLOAD_SIZE;\n\tif (!Number.isFinite(rawMax) || rawMax <= 0) {\n\t\treturn fail(\"CONFIGURATION_ERROR\", \"Invalid maxUploadSize configuration\");\n\t}\n\n\tconst acquired = await acquireBytes(input, rawMax);\n\tif (\"success\" in acquired) return acquired;\n\tconst { bytes } = acquired;\n\n\t// Validate the raw MIME string before normalize/allowlist: normalizeMime\n\t// only strips parameters and matchesMimeAllowlist only checks startsWith,\n\t// so without this a crafted value like \"image/png\\r\\nX-Evil: 1\" would\n\t// reach the storage backend's ContentType header and be echoed by the\n\t// media file serving route.\n\tif (!CONTENT_TYPE_RE.test(acquired.mimeType)) {\n\t\treturn fail(\"VALIDATION_ERROR\", \"Invalid content type\");\n\t}\n\tconst mimeType = normalizeMime(acquired.mimeType);\n\n\tif (!matchesMimeAllowlist(mimeType, GLOBAL_UPLOAD_ALLOWLIST)) {\n\t\treturn fail(\"INVALID_TYPE\", \"File type not allowed\");\n\t}\n\tif (bytes.byteLength > rawMax) {\n\t\treturn fail(\"PAYLOAD_TOO_LARGE\", `File exceeds maximum size of ${formatFileSize(rawMax)}`);\n\t}\n\n\ttry {\n\t\tconst contentHash = await computeContentHash(bytes);\n\t\tconst repo = new MediaRepository(db);\n\n\t\tconst existing = await repo.findByContentHash(contentHash);\n\t\tif (existing) {\n\t\t\treturn { success: true, data: { item: withUrl(existing), deduplicated: true } };\n\t\t}\n\n\t\tconst storageKey = `${ulid()}${path.extname(input.filename)}`;\n\t\tawait storage.upload({ key: storageKey, body: bytes, contentType: mimeType });\n\n\t\ttry {\n\t\t\tconst enriched = await enrichImageMetadata(bytes, mimeType);\n\t\t\tconst item = await repo.create({\n\t\t\t\tfilename: input.filename,\n\t\t\t\tmimeType,\n\t\t\t\tsize: bytes.byteLength,\n\t\t\t\twidth: enriched.width,\n\t\t\t\theight: enriched.height,\n\t\t\t\talt: input.alt,\n\t\t\t\tstorageKey,\n\t\t\t\tcontentHash,\n\t\t\t\tblurhash: enriched.blurhash,\n\t\t\t\tdominantColor: enriched.dominantColor,\n\t\t\t\tauthorId: input.authorId,\n\t\t\t});\n\t\t\treturn { success: true, data: { item: withUrl(item) } };\n\t\t} catch (error) {\n\t\t\t// Don't leave an orphaned object in storage when record creation fails\n\t\t\ttry {\n\t\t\t\tawait storage.delete(storageKey);\n\t\t\t} catch {\n\t\t\t\t// Ignore cleanup errors\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t} catch {\n\t\treturn f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EAAE,MAAM,QAbzB,MAAM,KAAK,OAAO;KAC9B,UAAU,MAAM;KAChB;KACA,MAAM,MAAM;KACZ,OAAO,SAAS;KAChB,QAAQ,SAAS;KACjB,KAAK,MAAM;KACX;KACA;KACA,UAAU,SAAS;KACnB,eAAe,SAAS;KACxB,UAAU,MAAM;KAChB,CAAC,CACiD,EAAE;IAAE;WAC/C,OAAO;AAEf,OAAI;AACH,UAAM,QAAQ,OAAO,WAAW;WACzB;AAGR,SAAM;;SAEA;AACP,SAAO,KAAK,gBAAgB,gBAAgB"}
|
|
1
|
+
{"version":3,"file":"media-upload-DNu3QySc.mjs","names":[],"sources":["../src/api/handlers/media-upload.ts"],"sourcesContent":["/**\n * Programmatic media upload handler (MCP `media_upload` tool).\n *\n * Accepts file bytes as base64 or fetches them from an external URL\n * (SSRF-guarded), then runs the same pipeline as the multipart REST\n * upload route: allowlist + size validation, content-hash deduplication,\n * storage upload, image metadata enrichment, and record creation.\n */\n\nimport * as path from \"node:path\";\n\nimport type { Kysely } from \"kysely\";\nimport { ulid } from \"ulidx\";\n\nimport { MediaRepository, type MediaItem } from \"../../database/repositories/media.js\";\nimport type { Database } from \"../../database/types.js\";\nimport { enrichImageMetadata } from \"../../media/enrich.js\";\nimport { matchesMimeAllowlist, normalizeMime } from \"../../media/mime.js\";\nimport { SsrfError, ssrfSafeFetch } from \"../../security/ssrf.js\";\nimport type { Storage } from \"../../storage/types.js\";\nimport { decodeBase64Bytes } from \"../../utils/base64.js\";\nimport { computeContentHash } from \"../../utils/hash.js\";\nimport { CONTENT_TYPE_RE, DEFAULT_MAX_UPLOAD_SIZE, formatFileSize } from \"../schemas/media.js\";\nimport type { ApiResult } from \"../types.js\";\nimport { GLOBAL_UPLOAD_ALLOWLIST } from \"./media-allowlist.js\";\n\nexport interface MediaUploadInput {\n\t/** Original filename (e.g. 'logo.png'); the extension is kept on the storage key. */\n\tfilename: string;\n\t/** Base64-encoded file contents. Exactly one of `base64` / `url` must be set. */\n\tbase64?: string;\n\t/** External http(s) URL to fetch the file from. Exactly one of `base64` / `url` must be set. */\n\turl?: string;\n\t/**\n\t * MIME type. Required with `base64`; optional with `url` (falls back to\n\t * the response's Content-Type header).\n\t */\n\tcontentType?: string;\n\t/** Alt text stored on the media record. */\n\talt?: string;\n\tauthorId?: string;\n\t/** Upload size limit in bytes (defaults to DEFAULT_MAX_UPLOAD_SIZE). */\n\tmaxUploadSize?: number;\n}\n\nexport type MediaUploadResult = ApiResult<{\n\titem: MediaItem & { url: string };\n\tdeduplicated?: boolean;\n}>;\n\nfunction fail(code: string, message: string): MediaUploadResult {\n\treturn { success: false, error: { code, message } };\n}\n\n/** Same relative-URL shape the REST media routes return. */\nfunction withUrl(item: MediaItem): MediaItem & { url: string } {\n\treturn { ...item, url: `/_emdash/api/media/file/${item.storageKey}` };\n}\n\n/** Strip parameters from a Content-Type header value (e.g. '; charset=...'). */\nfunction bareMime(headerValue: string): string {\n\treturn (headerValue.split(\";\")[0] ?? \"\").trim();\n}\n\n/**\n * Acquire the file bytes and MIME type from either the base64 payload or\n * the external URL. Returns an error result on any validation failure.\n */\nasync function acquireBytes(\n\tinput: MediaUploadInput,\n\tmaxUploadSize: number,\n): Promise<{ bytes: Uint8Array; mimeType: string } | MediaUploadResult> {\n\tif (input.base64) {\n\t\tif (!input.contentType) {\n\t\t\treturn fail(\"VALIDATION_ERROR\", \"contentType is required when uploading base64 data\");\n\t\t}\n\t\t// Cheap size precheck on the encoded string (decoded size is ~3/4 of\n\t\t// the base64 length) before allocating the decoded buffer.\n\t\tif ((input.base64.length * 3) / 4 > maxUploadSize) {\n\t\t\treturn fail(\n\t\t\t\t\"PAYLOAD_TOO_LARGE\",\n\t\t\t\t`File exceeds maximum size of ${formatFileSize(maxUploadSize)}`,\n\t\t\t);\n\t\t}\n\t\ttry {\n\t\t\treturn { bytes: decodeBase64Bytes(input.base64), mimeType: input.contentType };\n\t\t} catch {\n\t\t\treturn fail(\"VALIDATION_ERROR\", \"Invalid base64 data\");\n\t\t}\n\t}\n\n\t// url mode — the caller guarantees exactly one source, so url is set here\n\tconst url = input.url;\n\tif (!url) {\n\t\treturn fail(\"VALIDATION_ERROR\", \"Provide exactly one of 'base64' or 'url'\");\n\t}\n\tlet response: Response;\n\ttry {\n\t\tresponse = await ssrfSafeFetch(url, { headers: { accept: \"*/*\" } });\n\t} catch (error) {\n\t\tif (error instanceof SsrfError) {\n\t\t\treturn fail(\"VALIDATION_ERROR\", `URL not allowed: ${error.message}`);\n\t\t}\n\t\treturn fail(\"FETCH_ERROR\", \"Failed to fetch file from URL\");\n\t}\n\tif (!response.ok) {\n\t\treturn fail(\"FETCH_ERROR\", `Failed to fetch file from URL (HTTP ${response.status})`);\n\t}\n\n\tconst contentLength = response.headers.get(\"Content-Length\");\n\tif (contentLength && parseInt(contentLength, 10) > maxUploadSize) {\n\t\treturn fail(\n\t\t\t\"PAYLOAD_TOO_LARGE\",\n\t\t\t`File exceeds maximum size of ${formatFileSize(maxUploadSize)}`,\n\t\t);\n\t}\n\n\tconst mimeType = input.contentType ?? bareMime(response.headers.get(\"Content-Type\") ?? \"\");\n\tif (!mimeType) {\n\t\treturn fail(\"VALIDATION_ERROR\", \"Could not determine MIME type — pass contentType explicitly\");\n\t}\n\n\tconst bytes = new Uint8Array(await response.arrayBuffer());\n\treturn { bytes, mimeType };\n}\n\n/**\n * Upload a media file from base64 data or an external URL.\n *\n * Mirrors the REST `POST /_emdash/api/media` route: global MIME allowlist,\n * size limit, content-hash dedupe (returns the existing item with\n * `deduplicated: true`), storage upload with cleanup on failure, and\n * image metadata enrichment (dimensions, blurhash, dominant color).\n */\nexport async function handleMediaUpload(\n\tdb: Kysely<Database>,\n\tstorage: Storage,\n\tinput: MediaUploadInput,\n): Promise<MediaUploadResult> {\n\tif (!input.base64 === !input.url) {\n\t\treturn fail(\"VALIDATION_ERROR\", \"Provide exactly one of 'base64' or 'url'\");\n\t}\n\n\tconst rawMax = input.maxUploadSize ?? DEFAULT_MAX_UPLOAD_SIZE;\n\tif (!Number.isFinite(rawMax) || rawMax <= 0) {\n\t\treturn fail(\"CONFIGURATION_ERROR\", \"Invalid maxUploadSize configuration\");\n\t}\n\n\tconst acquired = await acquireBytes(input, rawMax);\n\tif (\"success\" in acquired) return acquired;\n\tconst { bytes } = acquired;\n\n\t// Validate the raw MIME string before normalize/allowlist: normalizeMime\n\t// only strips parameters and matchesMimeAllowlist only checks startsWith,\n\t// so without this a crafted value like \"image/png\\r\\nX-Evil: 1\" would\n\t// reach the storage backend's ContentType header and be echoed by the\n\t// media file serving route.\n\tif (!CONTENT_TYPE_RE.test(acquired.mimeType)) {\n\t\treturn fail(\"VALIDATION_ERROR\", \"Invalid content type\");\n\t}\n\tconst mimeType = normalizeMime(acquired.mimeType);\n\n\tif (!matchesMimeAllowlist(mimeType, GLOBAL_UPLOAD_ALLOWLIST)) {\n\t\treturn fail(\"INVALID_TYPE\", \"File type not allowed\");\n\t}\n\tif (bytes.byteLength > rawMax) {\n\t\treturn fail(\"PAYLOAD_TOO_LARGE\", `File exceeds maximum size of ${formatFileSize(rawMax)}`);\n\t}\n\n\ttry {\n\t\tconst contentHash = await computeContentHash(bytes);\n\t\tconst repo = new MediaRepository(db);\n\n\t\tconst existing = await repo.findByContentHash(contentHash);\n\t\tif (existing) {\n\t\t\treturn { success: true, data: { item: withUrl(existing), deduplicated: true } };\n\t\t}\n\n\t\tconst storageKey = `${ulid()}${path.extname(input.filename)}`;\n\t\tawait storage.upload({ key: storageKey, body: bytes, contentType: mimeType });\n\n\t\ttry {\n\t\t\tconst enriched = await enrichImageMetadata(bytes, mimeType);\n\t\t\tconst item = await repo.create({\n\t\t\t\tfilename: input.filename,\n\t\t\t\tmimeType,\n\t\t\t\tsize: bytes.byteLength,\n\t\t\t\twidth: enriched.width,\n\t\t\t\theight: enriched.height,\n\t\t\t\talt: input.alt,\n\t\t\t\tstorageKey,\n\t\t\t\tcontentHash,\n\t\t\t\tblurhash: enriched.blurhash,\n\t\t\t\tdominantColor: enriched.dominantColor,\n\t\t\t\tauthorId: input.authorId,\n\t\t\t});\n\t\t\treturn { success: true, data: { item: withUrl(item) } };\n\t\t} catch (error) {\n\t\t\t// Don't leave an orphaned object in storage when record creation fails\n\t\t\ttry {\n\t\t\t\tawait storage.delete(storageKey);\n\t\t\t} catch {\n\t\t\t\t// Ignore cleanup errors\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t} catch {\n\t\treturn fail(\"UPLOAD_ERROR\", \"Upload failed\");\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAkDA,SAAS,KAAK,MAAc,SAAoC;AAC/D,QAAO;EAAE,SAAS;EAAO,OAAO;GAAE;GAAM;GAAS;EAAE;;;AAIpD,SAAS,QAAQ,MAA8C;AAC9D,QAAO;EAAE,GAAG;EAAM,KAAK,2BAA2B,KAAK;EAAc;;;AAItE,SAAS,SAAS,aAA6B;AAC9C,SAAQ,YAAY,MAAM,IAAI,CAAC,MAAM,IAAI,MAAM;;;;;;AAOhD,eAAe,aACd,OACA,eACuE;AACvE,KAAI,MAAM,QAAQ;AACjB,MAAI,CAAC,MAAM,YACV,QAAO,KAAK,oBAAoB,qDAAqD;AAItF,MAAK,MAAM,OAAO,SAAS,IAAK,IAAI,cACnC,QAAO,KACN,qBACA,gCAAgC,eAAe,cAAc,GAC7D;AAEF,MAAI;AACH,UAAO;IAAE,OAAO,kBAAkB,MAAM,OAAO;IAAE,UAAU,MAAM;IAAa;UACvE;AACP,UAAO,KAAK,oBAAoB,sBAAsB;;;CAKxD,MAAM,MAAM,MAAM;AAClB,KAAI,CAAC,IACJ,QAAO,KAAK,oBAAoB,2CAA2C;CAE5E,IAAI;AACJ,KAAI;AACH,aAAW,MAAM,cAAc,KAAK,EAAE,SAAS,EAAE,QAAQ,OAAO,EAAE,CAAC;UAC3D,OAAO;AACf,MAAI,iBAAiB,UACpB,QAAO,KAAK,oBAAoB,oBAAoB,MAAM,UAAU;AAErE,SAAO,KAAK,eAAe,gCAAgC;;AAE5D,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SAAS;IAAE,cAAc;IAAM;GAAE;EAGhF,MAAM,aAAa,GAAG,MAAM,GAAG,KAAK,QAAQ,MAAM,SAAS;AAC3D,QAAM,QAAQ,OAAO;GAAE,KAAK;GAAY,MAAM;GAAO,aAAa;GAAU,CAAC;AAE7E,MAAI;GACH,MAAM,WAAW,MAAM,oBAAoB,OAAO,SAAS;AAc3D,UAAO;IAAE,SAAS;IAAM,MAAM,EAAE,MAAM,QAbzB,MAAM,KAAK,OAAO;KAC9B,UAAU,MAAM;KAChB;KACA,MAAM,MAAM;KACZ,OAAO,SAAS;KAChB,QAAQ,SAAS;KACjB,KAAK,MAAM;KACX;KACA;KACA,UAAU,SAAS;KACnB,eAAe,SAAS;KACxB,UAAU,MAAM;KAChB,CAAC,CACiD,EAAE;IAAE;WAC/C,OAAO;AAEf,OAAI;AACH,UAAM,QAAQ,OAAO,WAAW;WACzB;AAGR,SAAM;;SAEA;AACP,SAAO,KAAK,gBAAgB,gBAAgB"}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { o as __exportAll } from "./runner-
|
|
1
|
+
import { o as __exportAll } from "./runner-BdeLEgad.mjs";
|
|
2
2
|
import { t as validateIdentifier } from "./validate-VPnKoIzW.mjs";
|
|
3
|
-
import { n as chunks, t as SQL_BATCH_SIZE } from "./chunks-
|
|
4
|
-
import { n as InvalidCursorError } from "./types-
|
|
5
|
-
import { t as MediaRepository } from "./media-
|
|
6
|
-
import { d as loadContentMediaUsageSnapshots, f as MEDIA_USAGE_CONTENT_SOURCE_VARIANTS, g as MediaUsageRepository, h as loadContentMediaUsageFields, l as withContentUsageCollectionLock, m as MediaUsageFieldDiscoveryError, n as CONTENT_MEDIA_USAGE_COLLECTION_SCOPE, p as buildContentMediaUsageSourceKey, t as CONTENT_MEDIA_USAGE_ADAPTER_ID, u as CONTENT_SOURCE_SCHEMA_VERSION } from "./content-refresh-
|
|
3
|
+
import { n as chunks, t as SQL_BATCH_SIZE } from "./chunks-Bq-5DPrD.mjs";
|
|
4
|
+
import { n as InvalidCursorError } from "./types-CrRUFdej.mjs";
|
|
5
|
+
import { t as MediaRepository } from "./media-its1WLYv.mjs";
|
|
6
|
+
import { d as loadContentMediaUsageSnapshots, f as MEDIA_USAGE_CONTENT_SOURCE_VARIANTS, g as MediaUsageRepository, h as loadContentMediaUsageFields, l as withContentUsageCollectionLock, m as MediaUsageFieldDiscoveryError, n as CONTENT_MEDIA_USAGE_COLLECTION_SCOPE, p as buildContentMediaUsageSourceKey, t as CONTENT_MEDIA_USAGE_ADAPTER_ID, u as CONTENT_SOURCE_SCHEMA_VERSION } from "./content-refresh-CPMSauD3.mjs";
|
|
7
7
|
import { t as ErrorCode } from "./errors-DtEXIQQV.mjs";
|
|
8
8
|
import { sql } from "kysely";
|
|
9
9
|
import { ulid } from "ulidx";
|
|
@@ -551,4 +551,4 @@ function normalizeMediaUsageReferenceType(referenceType) {
|
|
|
551
551
|
|
|
552
552
|
//#endregion
|
|
553
553
|
export { media_usage_exports as i, handleMediaUsageRepair as n, handleMediaUsageSummaries as r, handleMediaUsageDetails as t };
|
|
554
|
-
//# sourceMappingURL=media-usage-
|
|
554
|
+
//# sourceMappingURL=media-usage-DPQ3K4xB.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"media-usage-CljdO1mc.mjs","names":[],"sources":["../src/media/usage/content-repair.ts","../src/api/handlers/media-usage.ts"],"sourcesContent":["import { sql, type Kysely } from \"kysely\";\nimport { ulid } from \"ulidx\";\n\nimport {\n\tMediaUsageRepository,\n\ttype MediaUsageSource,\n} from \"../../database/repositories/media-usage.js\";\nimport type { Database } from \"../../database/types.js\";\nimport { validateIdentifier } from \"../../database/validate.js\";\nimport { chunks, SQL_BATCH_SIZE } from \"../../utils/chunks.js\";\nimport {\n\tloadContentMediaUsageFields,\n\tMediaUsageFieldDiscoveryError,\n\ttype ContentMediaUsageFieldDiscovery,\n} from \"./content-fields.js\";\nimport {\n\tCONTENT_MEDIA_USAGE_ADAPTER_ID,\n\tCONTENT_MEDIA_USAGE_COLLECTION_SCOPE,\n\twithContentUsageCollectionLock,\n} from \"./content-refresh.js\";\nimport {\n\tCONTENT_SOURCE_SCHEMA_VERSION,\n\ttype ContentMediaUsageSnapshot,\n\tloadContentMediaUsageSnapshots,\n} from \"./content-snapshots.js\";\nimport {\n\tbuildContentMediaUsageSourceKey,\n\tMEDIA_USAGE_CONTENT_SOURCE_VARIANTS,\n} from \"./source-key.js\";\n\nexport type ContentMediaUsageRepairStatus = \"complete\" | \"partial\" | \"failed\" | \"stale\";\n\nexport const CONTENT_MEDIA_USAGE_REPAIR_ERROR = {\n\tCOLLECTION_NOT_FOUND: \"COLLECTION_NOT_FOUND\",\n\tCONTENT_NOT_FOUND: \"CONTENT_NOT_FOUND\",\n\tDRAFT_REVISION_NOT_FOUND: \"DRAFT_REVISION_NOT_FOUND\",\n\tDRAFT_REVISION_MISMATCH: \"DRAFT_REVISION_MISMATCH\",\n\tDRAFT_REVISION_INVALID: \"DRAFT_REVISION_INVALID\",\n\tCONTENT_USAGE_REPAIR_ERROR: \"CONTENT_USAGE_REPAIR_ERROR\",\n\tCONTENT_USAGE_REPAIR_CONFLICT: \"CONTENT_USAGE_REPAIR_CONFLICT\",\n\tINVALID_REPEATER_VALIDATION: \"INVALID_REPEATER_VALIDATION\",\n} as const;\n\nexport type ContentMediaUsageRepairErrorCode =\n\t(typeof CONTENT_MEDIA_USAGE_REPAIR_ERROR)[keyof typeof CONTENT_MEDIA_USAGE_REPAIR_ERROR];\n\nexport interface ContentMediaUsageRepairCollectionInput {\n\tcollectionSlug: string;\n}\n\nexport interface ContentMediaUsageRepairScope {\n\tadapterId: typeof CONTENT_MEDIA_USAGE_ADAPTER_ID;\n\tscopeType: typeof CONTENT_MEDIA_USAGE_COLLECTION_SCOPE;\n\tscopeKey: string;\n}\n\nexport interface ContentMediaUsageRepairCollectionResult {\n\tscope: ContentMediaUsageRepairScope;\n\tstatus: ContentMediaUsageRepairStatus;\n\tindexedSourceCount: number;\n\tfailedSourceCount: number;\n\tskippedSourceCount: number;\n\tdeletedSourceCount: number;\n\tlastErrorCode: string | null;\n\tstartedAt: string;\n\tcompletedAt: string | null;\n}\n\nexport interface ContentMediaUsageRepairAllResult {\n\tstatus: ContentMediaUsageRepairStatus;\n\tcollections: ContentMediaUsageRepairCollectionResult[];\n\tindexedSourceCount: number;\n\tfailedSourceCount: number;\n\tskippedSourceCount: number;\n\tdeletedSourceCount: number;\n}\n\nexport interface ContentMediaUsageCollectionScan {\n\tcollectionSlug: string;\n\tcontentIds: string[];\n}\n\ninterface ContentMediaUsageCollectionRecord {\n\tid: string;\n\tslug: string;\n}\n\ninterface ContentMediaUsageInitialCollectionResult {\n\tcollection: ContentMediaUsageCollectionRecord;\n\tresult: ContentMediaUsageRepairCollectionResult;\n}\n\nexport async function repairContentMediaUsageAll(\n\tdb: Kysely<Database>,\n): Promise<ContentMediaUsageRepairAllResult> {\n\tconst collections = await loadContentMediaUsageCollectionRecords(db);\n\tconst results: ContentMediaUsageInitialCollectionResult[] = [];\n\n\tfor (const collection of collections) {\n\t\tresults.push({\n\t\t\tcollection,\n\t\t\tresult: await repairContentMediaUsageCollectionSafely(db, collection.slug),\n\t\t});\n\t}\n\n\treturn aggregateContentMediaUsageRepairAll(\n\t\tawait filterExistingContentMediaUsageCollectionResults(db, results),\n\t);\n}\n\nexport async function scanContentMediaUsageCollection(\n\tdb: Kysely<Database>,\n\tcollectionSlug: string,\n): Promise<ContentMediaUsageCollectionScan | null> {\n\tvalidateIdentifier(collectionSlug, \"collection slug\");\n\tconst collection = await db\n\t\t.selectFrom(\"_emdash_collections\")\n\t\t.select(\"id\")\n\t\t.where(\"slug\", \"=\", collectionSlug)\n\t\t.executeTakeFirst();\n\tif (!collection) return null;\n\n\tconst tableName = getContentTableName(collectionSlug);\n\tconst rows = await sql<{ id: string }>`\n\t\tSELECT id\n\t\tFROM ${sql.ref(tableName)}\n\t\tORDER BY id ASC\n\t`.execute(db);\n\n\treturn {\n\t\tcollectionSlug,\n\t\tcontentIds: rows.rows.map((row) => row.id),\n\t};\n}\n\nexport async function repairContentMediaUsageCollection(\n\tdb: Kysely<Database>,\n\tinput: ContentMediaUsageRepairCollectionInput,\n): Promise<ContentMediaUsageRepairCollectionResult> {\n\tvalidateIdentifier(input.collectionSlug, \"collection slug\");\n\treturn withContentUsageCollectionLock(input.collectionSlug, () =>\n\t\trepairContentMediaUsageCollectionUnlocked(db, input.collectionSlug),\n\t);\n}\n\nasync function loadContentMediaUsageCollectionRecords(\n\tdb: Kysely<Database>,\n): Promise<ContentMediaUsageCollectionRecord[]> {\n\treturn db\n\t\t.selectFrom(\"_emdash_collections\")\n\t\t.select([\"id\", \"slug\"])\n\t\t.orderBy(\"slug\", \"asc\")\n\t\t.execute();\n}\n\nasync function repairContentMediaUsageCollectionSafely(\n\tdb: Kysely<Database>,\n\tcollectionSlug: string,\n): Promise<ContentMediaUsageRepairCollectionResult> {\n\ttry {\n\t\treturn await repairContentMediaUsageCollection(db, { collectionSlug });\n\t} catch (error) {\n\t\tconsole.error(`[media-usage] Failed to repair collection ${collectionSlug}:`, error);\n\t\tconst now = new Date().toISOString();\n\t\treturn {\n\t\t\tscope: contentMediaUsageCollectionScope(collectionSlug),\n\t\t\tstatus: \"failed\",\n\t\t\tindexedSourceCount: 0,\n\t\t\tfailedSourceCount: 0,\n\t\t\tskippedSourceCount: 0,\n\t\t\tdeletedSourceCount: 0,\n\t\t\tlastErrorCode: CONTENT_MEDIA_USAGE_REPAIR_ERROR.CONTENT_USAGE_REPAIR_ERROR,\n\t\t\tstartedAt: now,\n\t\t\tcompletedAt: now,\n\t\t};\n\t}\n}\n\nasync function filterExistingContentMediaUsageCollectionResults(\n\tdb: Kysely<Database>,\n\tresults: readonly ContentMediaUsageInitialCollectionResult[],\n): Promise<ContentMediaUsageRepairCollectionResult[]> {\n\tconst currentCollections = await loadContentMediaUsageCollectionRecordsSafely(db);\n\tconst currentIdsBySlug = new Map(\n\t\tcurrentCollections.map((collection) => [collection.slug, collection.id]),\n\t);\n\tconst includedResults: ContentMediaUsageRepairCollectionResult[] = [];\n\tconst excludedResults: ContentMediaUsageRepairCollectionResult[] = [];\n\n\tfor (const { collection, result } of results) {\n\t\tif (currentIdsBySlug.get(collection.slug) === collection.id) {\n\t\t\tincludedResults.push(result);\n\t\t} else {\n\t\t\texcludedResults.push(result);\n\t\t}\n\t}\n\n\tif (excludedResults.length > 0) {\n\t\tconst repo = new MediaUsageRepository(db);\n\t\tfor (const result of excludedResults) {\n\t\t\tawait repo.deleteIndexStatus(result.scope);\n\t\t}\n\t}\n\n\treturn includedResults;\n}\n\nasync function loadContentMediaUsageCollectionRecordsSafely(\n\tdb: Kysely<Database>,\n): Promise<ContentMediaUsageCollectionRecord[]> {\n\ttry {\n\t\treturn await loadContentMediaUsageCollectionRecords(db);\n\t} catch {\n\t\t// Retry once before failing; returning unpruned results can over-report deleted collections.\n\t}\n\n\ttry {\n\t\treturn await loadContentMediaUsageCollectionRecords(db);\n\t} catch (error) {\n\t\tconsole.error(\"[media-usage] Failed to reconcile all-content repair collections:\", error);\n\t\tthrow error;\n\t}\n}\n\nfunction aggregateContentMediaUsageRepairAll(\n\tcollections: readonly ContentMediaUsageRepairCollectionResult[],\n): ContentMediaUsageRepairAllResult {\n\treturn {\n\t\tstatus: determineRepairAllStatus(collections),\n\t\tcollections: [...collections],\n\t\tindexedSourceCount: sumCollectionRepairCount(collections, \"indexedSourceCount\"),\n\t\tfailedSourceCount: sumCollectionRepairCount(collections, \"failedSourceCount\"),\n\t\tskippedSourceCount: sumCollectionRepairCount(collections, \"skippedSourceCount\"),\n\t\tdeletedSourceCount: sumCollectionRepairCount(collections, \"deletedSourceCount\"),\n\t};\n}\n\nfunction determineRepairAllStatus(\n\tcollections: readonly ContentMediaUsageRepairCollectionResult[],\n): ContentMediaUsageRepairStatus {\n\tif (collections.length === 0) return \"complete\";\n\tif (collections.every((collection) => collection.status === \"complete\")) return \"complete\";\n\tif (collections.some((collection) => collection.status === \"stale\")) return \"stale\";\n\tif (collections.some((collection) => collection.status === \"partial\")) return \"partial\";\n\tif (collections.every((collection) => collection.status === \"failed\")) return \"failed\";\n\treturn \"partial\";\n}\n\nfunction sumCollectionRepairCount(\n\tcollections: readonly ContentMediaUsageRepairCollectionResult[],\n\tkey: \"indexedSourceCount\" | \"failedSourceCount\" | \"skippedSourceCount\" | \"deletedSourceCount\",\n): number {\n\treturn collections.reduce((sum, collection) => sum + collection[key], 0);\n}\n\nasync function repairContentMediaUsageCollectionUnlocked(\n\tdb: Kysely<Database>,\n\tcollectionSlug: string,\n): Promise<ContentMediaUsageRepairCollectionResult> {\n\tconst startedAt = new Date().toISOString();\n\tconst scope = contentMediaUsageCollectionScope(collectionSlug);\n\tif (!(await contentCollectionExists(db, collectionSlug))) {\n\t\treturn {\n\t\t\tscope,\n\t\t\tstatus: \"failed\",\n\t\t\tindexedSourceCount: 0,\n\t\t\tfailedSourceCount: 0,\n\t\t\tskippedSourceCount: 0,\n\t\t\tdeletedSourceCount: 0,\n\t\t\tlastErrorCode: CONTENT_MEDIA_USAGE_REPAIR_ERROR.COLLECTION_NOT_FOUND,\n\t\t\tstartedAt,\n\t\t\tcompletedAt: startedAt,\n\t\t};\n\t}\n\n\tconst repo = new MediaUsageRepository(db);\n\tconst runToken = ulid();\n\tawait repo.beginIndexStatusRepair({\n\t\t...scope,\n\t\trunToken,\n\t\tschemaVersion: CONTENT_SOURCE_SCHEMA_VERSION,\n\t\tstartedAt,\n\t});\n\n\ttry {\n\t\tconst scan = await scanContentMediaUsageCollection(db, collectionSlug);\n\t\tif (!scan) {\n\t\t\tconst completedAt = new Date().toISOString();\n\t\t\treturn await finalizeRepairStatus(repo, {\n\t\t\t\t...scope,\n\t\t\t\trunToken,\n\t\t\t\tcounts: {\n\t\t\t\t\tindexedSourceCount: 0,\n\t\t\t\t\tfailedSourceCount: 0,\n\t\t\t\t\tskippedSourceCount: 0,\n\t\t\t\t\tdeletedSourceCount: 0,\n\t\t\t\t\tlastErrorCode: CONTENT_MEDIA_USAGE_REPAIR_ERROR.COLLECTION_NOT_FOUND,\n\t\t\t\t\tmissingContentIds: new Set(),\n\t\t\t\t},\n\t\t\t\tstatus: \"failed\",\n\t\t\t\tstartedAt,\n\t\t\t\tcompletedAt,\n\t\t\t});\n\t\t}\n\t\tconst counts = await repairScannedContentSources(db, repo, scan);\n\t\tconst finalScan = await scanContentMediaUsageCollection(db, collectionSlug);\n\t\tif (!finalScan) {\n\t\t\tcounts.failedSourceCount++;\n\t\t\tcounts.lastErrorCode = CONTENT_MEDIA_USAGE_REPAIR_ERROR.COLLECTION_NOT_FOUND;\n\t\t} else if (!sameContentIds(repairedContentIds(scan.contentIds, counts), finalScan.contentIds)) {\n\t\t\tmarkRepairConflict(counts);\n\t\t}\n\t\tconst completedAt = new Date().toISOString();\n\t\tconst status = determineRepairStatus(counts);\n\t\treturn await finalizeRepairStatus(repo, {\n\t\t\t...scope,\n\t\t\trunToken,\n\t\t\tcounts,\n\t\t\tstatus,\n\t\t\tstartedAt,\n\t\t\tcompletedAt,\n\t\t});\n\t} catch (error) {\n\t\tif (!(error instanceof MediaUsageFieldDiscoveryError)) {\n\t\t\tconsole.error(`[media-usage] Failed to repair collection ${collectionSlug}:`, error);\n\t\t}\n\t\tconst completedAt = new Date().toISOString();\n\t\tconst lastErrorCode =\n\t\t\terror instanceof MediaUsageFieldDiscoveryError\n\t\t\t\t? error.code\n\t\t\t\t: CONTENT_MEDIA_USAGE_REPAIR_ERROR.CONTENT_USAGE_REPAIR_ERROR;\n\t\treturn finalizeRepairStatus(repo, {\n\t\t\t...scope,\n\t\t\trunToken,\n\t\t\tcounts: {\n\t\t\t\tindexedSourceCount: 0,\n\t\t\t\tfailedSourceCount: 0,\n\t\t\t\tskippedSourceCount: 0,\n\t\t\t\tdeletedSourceCount: 0,\n\t\t\t\tlastErrorCode,\n\t\t\t\tmissingContentIds: new Set(),\n\t\t\t},\n\t\t\tstatus: \"failed\",\n\t\t\tstartedAt,\n\t\t\tcompletedAt,\n\t\t});\n\t}\n}\n\ninterface RepairCounts {\n\tindexedSourceCount: number;\n\tfailedSourceCount: number;\n\tskippedSourceCount: number;\n\tdeletedSourceCount: number;\n\tlastErrorCode: ContentMediaUsageRepairErrorCode | null;\n\tmissingContentIds: Set<string>;\n}\n\nasync function repairScannedContentSources(\n\tdb: Kysely<Database>,\n\trepo: MediaUsageRepository,\n\tscan: ContentMediaUsageCollectionScan,\n): Promise<RepairCounts> {\n\tconst counts: RepairCounts = {\n\t\tindexedSourceCount: 0,\n\t\tfailedSourceCount: 0,\n\t\tskippedSourceCount: 0,\n\t\tdeletedSourceCount: 0,\n\t\tlastErrorCode: null,\n\t\tmissingContentIds: new Set(),\n\t};\n\n\tconst fieldDiscovery = await loadContentMediaUsageFields(db, scan.collectionSlug);\n\tconst observedSources = await repo.findSources(buildContentSourceKeysForScan(scan));\n\n\tfor (const contentId of scan.contentIds) {\n\t\tawait repairContentSource(\n\t\t\tdb,\n\t\t\trepo,\n\t\t\tscan.collectionSlug,\n\t\t\tcontentId,\n\t\t\tfieldDiscovery,\n\t\t\tobservedSources,\n\t\t\tcounts,\n\t\t);\n\t}\n\n\tawait reconcileOrphanedContentSources(db, repo, scan.collectionSlug, counts);\n\treturn counts;\n}\n\nasync function repairContentSource(\n\tdb: Kysely<Database>,\n\trepo: MediaUsageRepository,\n\tcollectionSlug: string,\n\tcontentId: string,\n\tfieldDiscovery: ContentMediaUsageFieldDiscovery,\n\tobservedSources: Map<string, MediaUsageSource>,\n\tcounts: RepairCounts,\n): Promise<void> {\n\tconst sourceKeys = buildContentSourceKeys(collectionSlug, contentId);\n\tconst snapshotsResult = await loadContentMediaUsageSnapshots(\n\t\tdb,\n\t\tcollectionSlug,\n\t\tcontentId,\n\t\tfieldDiscovery,\n\t);\n\tif (!snapshotsResult.success) {\n\t\tif (snapshotsResult.error === CONTENT_MEDIA_USAGE_REPAIR_ERROR.CONTENT_NOT_FOUND) {\n\t\t\tmarkRepairConflict(counts);\n\t\t\tcounts.missingContentIds.add(contentId);\n\t\t\treturn;\n\t\t}\n\t\tcounts.lastErrorCode = snapshotsResult.error;\n\t\tif (snapshotsResult.snapshots) {\n\t\t\t// Partial snapshot failures keep absent variants in place; the attempted source is marked below.\n\t\t\tawait repairSnapshotSources(repo, snapshotsResult.snapshots, observedSources, counts);\n\t\t}\n\t\tif (snapshotsResult.source) {\n\t\t\tconst result = await repo.markSourceAttemptedIfMatching(\n\t\t\t\t{\n\t\t\t\t\t...snapshotsResult.source,\n\t\t\t\t\tsourceCompleteness: \"failed\",\n\t\t\t\t\tlastErrorCode: snapshotsResult.error,\n\t\t\t\t},\n\t\t\t\tobservedSources.get(snapshotsResult.source.sourceKey) ?? null,\n\t\t\t);\n\t\t\tif (result.attempted) {\n\t\t\t\tcounts.failedSourceCount++;\n\t\t\t} else {\n\t\t\t\tmarkRepairConflict(counts);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tcounts.failedSourceCount++;\n\t\treturn;\n\t}\n\n\tconst expectedSourceKeys = await repairSnapshotSources(\n\t\trepo,\n\t\tsnapshotsResult.snapshots,\n\t\tobservedSources,\n\t\tcounts,\n\t);\n\n\tfor (const sourceKey of sourceKeys) {\n\t\tif (expectedSourceKeys.has(sourceKey)) continue;\n\t\tconst observedSource = observedSources.get(sourceKey);\n\t\tif (!observedSource) continue;\n\t\tawait deleteObservedSource(repo, sourceKey, observedSource, counts);\n\t}\n}\n\nasync function repairSnapshotSources(\n\trepo: MediaUsageRepository,\n\tsnapshots: readonly ContentMediaUsageSnapshot[],\n\tobservedSources: Map<string, MediaUsageSource>,\n\tcounts: RepairCounts,\n): Promise<Set<string>> {\n\tconst expectedSourceKeys = new Set<string>();\n\tfor (const snapshot of snapshots) {\n\t\texpectedSourceKeys.add(snapshot.source.sourceKey);\n\t\tconst result = await repo.replaceSourceIfMatching(\n\t\t\tsnapshot.source,\n\t\t\tsnapshot.occurrences,\n\t\t\tobservedSources.get(snapshot.source.sourceKey) ?? null,\n\t\t);\n\t\tif (result.replaced) {\n\t\t\tcounts.indexedSourceCount++;\n\t\t} else {\n\t\t\tmarkRepairConflict(counts);\n\t\t}\n\t}\n\treturn expectedSourceKeys;\n}\n\nfunction markRepairConflict(counts: RepairCounts): void {\n\tcounts.skippedSourceCount++;\n\tcounts.lastErrorCode ??= CONTENT_MEDIA_USAGE_REPAIR_ERROR.CONTENT_USAGE_REPAIR_CONFLICT;\n}\n\nasync function reconcileOrphanedContentSources(\n\tdb: Kysely<Database>,\n\trepo: MediaUsageRepository,\n\tcollectionSlug: string,\n\tcounts: RepairCounts,\n): Promise<void> {\n\tconst sources = await repo.findCollectionContentSources(collectionSlug);\n\tconst existingContentIds = await findExistingContentIds(\n\t\tdb,\n\t\tcollectionSlug,\n\t\tsources.flatMap((source) => (source.contentId ? [source.contentId] : [])),\n\t);\n\n\tfor (const source of sources) {\n\t\tif (!source.contentId) {\n\t\t\tawait deleteObservedSource(repo, source.sourceKey, source, counts);\n\t\t\tcontinue;\n\t\t}\n\t\tif (existingContentIds.has(source.contentId)) continue;\n\t\tawait deleteObservedSourceIfContentAbsent(repo, collectionSlug, source, counts);\n\t}\n}\n\nasync function findExistingContentIds(\n\tdb: Kysely<Database>,\n\tcollectionSlug: string,\n\tcontentIds: readonly string[],\n): Promise<Set<string>> {\n\tvalidateIdentifier(collectionSlug, \"collection slug\");\n\tconst existingContentIds = new Set<string>();\n\tconst uniqueContentIds = [...new Set(contentIds)];\n\tif (uniqueContentIds.length === 0) return existingContentIds;\n\n\tconst tableName = getContentTableName(collectionSlug);\n\tfor (const contentIdBatch of chunks(uniqueContentIds, SQL_BATCH_SIZE)) {\n\t\tconst result = await sql<{ id: string }>`\n\t\t\tSELECT id\n\t\t\tFROM ${sql.ref(tableName)}\n\t\t\tWHERE id IN (${sql.join(contentIdBatch)})\n\t\t`.execute(db);\n\t\tfor (const row of result.rows) {\n\t\t\texistingContentIds.add(row.id);\n\t\t}\n\t}\n\n\treturn existingContentIds;\n}\n\nasync function deleteObservedSourceIfContentAbsent(\n\trepo: MediaUsageRepository,\n\tcollectionSlug: string,\n\tobservedSource: MediaUsageSource,\n\tcounts: RepairCounts,\n): Promise<void> {\n\tif (!observedSource.contentId) return;\n\tconst result = await repo.deleteSourceIfMatchingContentAbsent(\n\t\tobservedSource.sourceKey,\n\t\tobservedSource,\n\t\tcollectionSlug,\n\t\tobservedSource.contentId,\n\t);\n\tif (result.deleted) {\n\t\tcounts.deletedSourceCount++;\n\t\treturn;\n\t}\n\tif (result.contentPresent) return;\n\tif (result.source) {\n\t\tmarkRepairConflict(counts);\n\t}\n}\n\nasync function deleteObservedSource(\n\trepo: MediaUsageRepository,\n\tsourceKey: string,\n\tobservedSource: MediaUsageSource,\n\tcounts: RepairCounts,\n): Promise<void> {\n\tconst result = await repo.deleteSourceIfMatching(sourceKey, observedSource);\n\tif (result.deleted) {\n\t\tcounts.deletedSourceCount++;\n\t\treturn;\n\t}\n\tif (result.source) {\n\t\tmarkRepairConflict(counts);\n\t}\n}\n\ninterface FinalizeInput extends ContentMediaUsageRepairScope {\n\trunToken: string;\n\tcounts: RepairCounts;\n\tstatus: Exclude<ContentMediaUsageRepairStatus, \"stale\">;\n\tstartedAt: string;\n\tcompletedAt: string;\n}\n\nasync function finalizeRepairStatus(\n\trepo: MediaUsageRepository,\n\tinput: FinalizeInput,\n): Promise<ContentMediaUsageRepairCollectionResult> {\n\tconst result = await repo.finalizeIndexStatusRepairIfRunning({\n\t\tadapterId: input.adapterId,\n\t\tscopeType: input.scopeType,\n\t\tscopeKey: input.scopeKey,\n\t\trunToken: input.runToken,\n\t\tstatus: input.status,\n\t\tschemaVersion: CONTENT_SOURCE_SCHEMA_VERSION,\n\t\tcompletedAt: input.completedAt,\n\t\tindexedSourceCount: input.counts.indexedSourceCount,\n\t\tfailedSourceCount: input.counts.failedSourceCount,\n\t\tlastErrorCode: input.counts.lastErrorCode,\n\t});\n\n\treturn {\n\t\tscope: {\n\t\t\tadapterId: input.adapterId,\n\t\t\tscopeType: input.scopeType,\n\t\t\tscopeKey: input.scopeKey,\n\t\t},\n\t\tstatus: result.finalized ? input.status : \"stale\",\n\t\tindexedSourceCount: input.counts.indexedSourceCount,\n\t\tfailedSourceCount: input.counts.failedSourceCount,\n\t\tskippedSourceCount: input.counts.skippedSourceCount,\n\t\tdeletedSourceCount: input.counts.deletedSourceCount,\n\t\tlastErrorCode: result.finalized\n\t\t\t? input.counts.lastErrorCode\n\t\t\t: (result.status?.lastErrorCode ??\n\t\t\t\tCONTENT_MEDIA_USAGE_REPAIR_ERROR.CONTENT_USAGE_REPAIR_CONFLICT),\n\t\tstartedAt: input.startedAt,\n\t\tcompletedAt: result.finalized ? input.completedAt : null,\n\t};\n}\n\nfunction determineRepairStatus(\n\tcounts: RepairCounts,\n): Exclude<ContentMediaUsageRepairStatus, \"stale\"> {\n\tif (counts.failedSourceCount === 0 && counts.skippedSourceCount === 0) return \"complete\";\n\tconst trustedProgress = counts.indexedSourceCount + counts.deletedSourceCount;\n\tif (counts.failedSourceCount > 0 && trustedProgress === 0) {\n\t\treturn \"failed\";\n\t}\n\treturn \"partial\";\n}\n\nfunction buildContentSourceKeys(collectionSlug: string, contentId: string): string[] {\n\treturn MEDIA_USAGE_CONTENT_SOURCE_VARIANTS.map((sourceVariant) =>\n\t\tbuildContentMediaUsageSourceKey({ collectionSlug, contentId, sourceVariant }),\n\t);\n}\n\nfunction buildContentSourceKeysForScan(scan: ContentMediaUsageCollectionScan): string[] {\n\treturn scan.contentIds.flatMap((contentId) =>\n\t\tbuildContentSourceKeys(scan.collectionSlug, contentId),\n\t);\n}\n\nasync function contentCollectionExists(\n\tdb: Kysely<Database>,\n\tcollectionSlug: string,\n): Promise<boolean> {\n\tconst row = await db\n\t\t.selectFrom(\"_emdash_collections\")\n\t\t.select(\"id\")\n\t\t.where(\"slug\", \"=\", collectionSlug)\n\t\t.executeTakeFirst();\n\treturn row !== undefined;\n}\n\nfunction sameContentIds(left: readonly string[], right: readonly string[]): boolean {\n\tif (left.length !== right.length) return false;\n\tconst rightIds = new Set(right);\n\treturn left.every((id) => rightIds.has(id));\n}\n\nfunction repairedContentIds(\n\tcontentIds: readonly string[],\n\tcounts: Pick<RepairCounts, \"missingContentIds\">,\n): string[] {\n\tif (counts.missingContentIds.size === 0) return [...contentIds];\n\treturn contentIds.filter((contentId) => !counts.missingContentIds.has(contentId));\n}\n\nfunction contentMediaUsageCollectionScope(collectionSlug: string): ContentMediaUsageRepairScope {\n\treturn {\n\t\tadapterId: CONTENT_MEDIA_USAGE_ADAPTER_ID,\n\t\tscopeType: CONTENT_MEDIA_USAGE_COLLECTION_SCOPE,\n\t\tscopeKey: collectionSlug,\n\t};\n}\n\nfunction getContentTableName(collectionSlug: string): string {\n\tvalidateIdentifier(collectionSlug, \"collection slug\");\n\treturn `ec_${collectionSlug}`;\n}\n","import type { Kysely } from \"kysely\";\n\nimport {\n\tMediaUsageRepository,\n\ttype MediaUsageCollectionIndexStatusScope,\n\ttype MediaUsageEntryGroup,\n} from \"../../database/repositories/media-usage.js\";\nimport { MediaRepository } from \"../../database/repositories/media.js\";\nimport { InvalidCursorError } from \"../../database/repositories/types.js\";\nimport type { Database } from \"../../database/types.js\";\nimport {\n\tCONTENT_MEDIA_USAGE_ADAPTER_ID,\n\tCONTENT_MEDIA_USAGE_COLLECTION_SCOPE,\n} from \"../../media/usage/content-refresh.js\";\nimport {\n\trepairContentMediaUsageAll,\n\trepairContentMediaUsageCollection,\n\ttype ContentMediaUsageRepairAllResult,\n\ttype ContentMediaUsageRepairCollectionResult,\n} from \"../../media/usage/content-repair.js\";\nimport { CONTENT_SOURCE_SCHEMA_VERSION } from \"../../media/usage/content-snapshots.js\";\nimport { ErrorCode } from \"../errors.js\";\nimport type {\n\tMediaUsageCoverage,\n\tMediaUsageCoverageStatus,\n\tMediaUsageDetailsResponse,\n\tMediaUsageEntryDetail,\n\tMediaUsageOccurrenceDetail,\n\tMediaUsageRepairRequest,\n\tMediaUsageRepairResponse,\n\tMediaUsageSummary,\n} from \"../schemas/media-usage.js\";\nimport type { ApiResult } from \"../types.js\";\n\nexport type {\n\tMediaUsageCoverage,\n\tMediaUsageCoverageStatus,\n\tMediaUsageDetailsResponse,\n\tMediaUsageEntryDetail,\n\tMediaUsageOccurrenceDetail,\n\tMediaUsageSourceDetail,\n\tMediaUsageRepairRequest,\n\tMediaUsageRepairResponse,\n\tMediaUsageSummary,\n} from \"../schemas/media-usage.js\";\n\ntype ContentMediaUsageRepairResult =\n\t| ContentMediaUsageRepairCollectionResult\n\t| ContentMediaUsageRepairAllResult;\n\nexport function aggregateMediaUsageCoverageStatus(\n\tscopes: readonly MediaUsageCollectionIndexStatusScope[],\n): MediaUsageCoverageStatus {\n\tconst statuses = scopes.map(normalizeMediaUsageCoverageStatus);\n\tif (statuses.every((status) => status === \"complete\")) {\n\t\treturn \"complete\";\n\t}\n\tif (statuses.includes(\"unknown\")) return \"unknown\";\n\tif (statuses.includes(\"running\")) return \"running\";\n\tif (statuses.includes(\"stale\")) return \"stale\";\n\tif (statuses.includes(\"partial\")) return \"partial\";\n\tif (statuses.every((status) => status === \"never\")) return \"never\";\n\tif (statuses.every((status) => status === \"failed\")) return \"failed\";\n\treturn \"partial\";\n}\n\nexport async function handleMediaUsageSummaries(\n\tdb: Kysely<Database>,\n\tmediaIds: readonly string[],\n\toptions: { includeCount: boolean },\n): Promise<ApiResult<Record<string, MediaUsageSummary>>> {\n\tif (mediaIds.length === 0) return { success: true, data: {} };\n\n\ttry {\n\t\tconst repository = new MediaUsageRepository(db);\n\t\tconst coverage = await loadMediaUsageCoverage(repository);\n\t\tconst counts = options.includeCount\n\t\t\t? await repository.findActiveEntryCountsByMediaIds(mediaIds)\n\t\t\t: null;\n\t\tconst summaries: Record<string, MediaUsageSummary> = {};\n\n\t\tfor (const mediaId of new Set(mediaIds)) {\n\t\t\tsummaries[mediaId] = {\n\t\t\t\tcount: counts ? (counts.get(mediaId) ?? 0) : null,\n\t\t\t\tcoverage,\n\t\t\t};\n\t\t}\n\n\t\treturn { success: true, data: summaries };\n\t} catch (error) {\n\t\tconsole.error(\"[media-usage] summary read failed:\", error);\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: {\n\t\t\t\tcode: ErrorCode.MEDIA_USAGE_READ_ERROR,\n\t\t\t\tmessage: \"Failed to read media usage\",\n\t\t\t},\n\t\t};\n\t}\n}\n\nexport async function handleMediaUsageDetails(\n\tdb: Kysely<Database>,\n\tmediaId: string,\n\toptions: { cursor?: string; limit?: number },\n): Promise<ApiResult<MediaUsageDetailsResponse>> {\n\ttry {\n\t\tconst media = await new MediaRepository(db).findById(mediaId);\n\t\tif (!media) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: {\n\t\t\t\t\tcode: ErrorCode.NOT_FOUND,\n\t\t\t\t\tmessage: `Media item not found: ${mediaId}`,\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\tconst repository = new MediaUsageRepository(db);\n\t\tconst coverage = await loadMediaUsageCoverage(repository);\n\t\tconst page = await repository.findCurrentEntryUsagePageByMediaId(mediaId, options);\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tdata: {\n\t\t\t\titems: page.items.map(toMediaUsageEntryDetail),\n\t\t\t\t...(page.nextCursor ? { nextCursor: page.nextCursor } : {}),\n\t\t\t\tcoverage,\n\t\t\t},\n\t\t};\n\t} catch (error) {\n\t\tif (error instanceof InvalidCursorError) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: ErrorCode.INVALID_CURSOR, message: error.message },\n\t\t\t};\n\t\t}\n\t\tconsole.error(\"[media-usage] detail read failed:\", error);\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: {\n\t\t\t\tcode: ErrorCode.MEDIA_USAGE_READ_ERROR,\n\t\t\t\tmessage: \"Failed to read media usage\",\n\t\t\t},\n\t\t};\n\t}\n}\n\nexport async function handleMediaUsageRepair(\n\tdb: Kysely<Database>,\n\tinput: MediaUsageRepairRequest,\n): Promise<ApiResult<MediaUsageRepairResponse>> {\n\ttry {\n\t\tlet result: ContentMediaUsageRepairResult;\n\t\tif (input.scope === \"collection\") {\n\t\t\tresult = await repairContentMediaUsageCollection(db, { collectionSlug: input.collection });\n\t\t} else if (input.scope === \"all\") {\n\t\t\tresult = await repairContentMediaUsageAll(db);\n\t\t} else {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: {\n\t\t\t\t\tcode: ErrorCode.VALIDATION_ERROR,\n\t\t\t\t\tmessage: \"Invalid media usage repair request\",\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\treturn { success: true, data: toMediaUsageRepairResponse(result) };\n\t} catch (error) {\n\t\tconsole.error(\"[media-usage] repair failed:\", error);\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: {\n\t\t\t\tcode: ErrorCode.MEDIA_USAGE_REPAIR_ERROR,\n\t\t\t\tmessage: \"Failed to repair media usage\",\n\t\t\t},\n\t\t};\n\t}\n}\n\nexport function toMediaUsageRepairResponse(\n\tresult: ContentMediaUsageRepairResult,\n): MediaUsageRepairResponse {\n\tconst collections = \"collections\" in result ? result.collections : [result];\n\n\treturn {\n\t\tstatus: result.status,\n\t\tindexedSourceCount: result.indexedSourceCount,\n\t\tfailedSourceCount: result.failedSourceCount,\n\t\tskippedSourceCount: result.skippedSourceCount,\n\t\tdeletedSourceCount: result.deletedSourceCount,\n\t\tcollections: collections.map(toMediaUsageRepairCollectionSummary),\n\t};\n}\n\nfunction toMediaUsageRepairCollectionSummary(result: ContentMediaUsageRepairCollectionResult) {\n\treturn {\n\t\tcollection: result.scope.scopeKey,\n\t\tstatus: result.status,\n\t\tindexedSourceCount: result.indexedSourceCount,\n\t\tfailedSourceCount: result.failedSourceCount,\n\t\tskippedSourceCount: result.skippedSourceCount,\n\t\tdeletedSourceCount: result.deletedSourceCount,\n\t\tlastErrorCode: result.lastErrorCode,\n\t\tstartedAt: result.startedAt,\n\t\tcompletedAt: result.completedAt,\n\t};\n}\n\nfunction normalizeMediaUsageCoverageStatus(\n\tscope: MediaUsageCollectionIndexStatusScope,\n): MediaUsageCoverageStatus {\n\tif (scope.status === null) return \"never\";\n\tif (scope.status === \"complete\") {\n\t\treturn scope.schemaVersion === CONTENT_SOURCE_SCHEMA_VERSION ? \"complete\" : \"stale\";\n\t}\n\tif (\n\t\tscope.status === \"never\" ||\n\t\tscope.status === \"running\" ||\n\t\tscope.status === \"partial\" ||\n\t\tscope.status === \"failed\" ||\n\t\tscope.status === \"stale\"\n\t) {\n\t\treturn scope.status;\n\t}\n\treturn \"unknown\";\n}\n\nasync function loadMediaUsageCoverage(\n\trepository: MediaUsageRepository,\n): Promise<MediaUsageCoverage> {\n\tconst scopes = await repository.findCollectionIndexStatusScopes({\n\t\tadapterId: CONTENT_MEDIA_USAGE_ADAPTER_ID,\n\t\tscopeType: CONTENT_MEDIA_USAGE_COLLECTION_SCOPE,\n\t});\n\treturn {\n\t\tscope: \"all_content_collections\",\n\t\tstatus: aggregateMediaUsageCoverageStatus(scopes),\n\t};\n}\n\nfunction toMediaUsageEntryDetail(group: MediaUsageEntryGroup): MediaUsageEntryDetail {\n\tconst preferred =\n\t\tgroup.sources.find(({ source }) => source.sourceVariant === \"draft_overlay\") ??\n\t\tgroup.sources.find(({ source }) => source.sourceVariant === \"columns\");\n\tif (!preferred) {\n\t\tthrow new Error(\"Media usage entry has no supported source\");\n\t}\n\n\treturn {\n\t\tcollection: group.collectionSlug,\n\t\tcontentId: group.contentId,\n\t\ttitle: preferred.source.contentTitle,\n\t\tslug: preferred.source.contentSlug,\n\t\tlocale: preferred.source.locale,\n\t\tstatus: preferred.source.contentStatus,\n\t\tscheduledAt: preferred.source.contentScheduledAt,\n\t\tdeletedAt: group.contentDeletedAt,\n\t\tsources: group.sources.flatMap(({ source, occurrences }) => {\n\t\t\tif (source.sourceVariant !== \"columns\" && source.sourceVariant !== \"draft_overlay\") {\n\t\t\t\treturn [];\n\t\t\t}\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\tvariant: source.sourceVariant,\n\t\t\t\t\toccurrences: occurrences.map((occurrence) => ({\n\t\t\t\t\t\tfieldSlug: occurrence.fieldSlug,\n\t\t\t\t\t\tfieldPath: occurrence.fieldPath,\n\t\t\t\t\t\toccurrenceIndex: occurrence.occurrenceIndex,\n\t\t\t\t\t\treferenceType: normalizeMediaUsageReferenceType(occurrence.referenceType),\n\t\t\t\t\t})),\n\t\t\t\t},\n\t\t\t];\n\t\t}),\n\t};\n}\n\nfunction normalizeMediaUsageReferenceType(\n\treferenceType: string,\n): MediaUsageOccurrenceDetail[\"referenceType\"] {\n\tif (\n\t\treferenceType === \"image_field\" ||\n\t\treferenceType === \"file_field\" ||\n\t\treferenceType === \"portable_text_image\"\n\t) {\n\t\treturn referenceType;\n\t}\n\treturn \"unknown\";\n}\n"],"mappings":";;;;;;;;;;;AAgCA,MAAa,mCAAmC;CAC/C,sBAAsB;CACtB,mBAAmB;CACnB,0BAA0B;CAC1B,yBAAyB;CACzB,wBAAwB;CACxB,4BAA4B;CAC5B,+BAA+B;CAC/B,6BAA6B;CAC7B;AAmDD,eAAsB,2BACrB,IAC4C;CAC5C,MAAM,cAAc,MAAM,uCAAuC,GAAG;CACpE,MAAM,UAAsD,EAAE;AAE9D,MAAK,MAAM,cAAc,YACxB,SAAQ,KAAK;EACZ;EACA,QAAQ,MAAM,wCAAwC,IAAI,WAAW,KAAK;EAC1E,CAAC;AAGH,QAAO,oCACN,MAAM,iDAAiD,IAAI,QAAQ,CACnE;;AAGF,eAAsB,gCACrB,IACA,gBACkD;AAClD,oBAAmB,gBAAgB,kBAAkB;AAMrD,KAAI,CALe,MAAM,GACvB,WAAW,sBAAsB,CACjC,OAAO,KAAK,CACZ,MAAM,QAAQ,KAAK,eAAe,CAClC,kBAAkB,CACH,QAAO;CAExB,MAAM,YAAY,oBAAoB,eAAe;AAOrD,QAAO;EACN;EACA,aARY,MAAM,GAAmB;;SAE9B,IAAI,IAAI,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;AAEd,QAAO;;AAGR,eAAe,uBACd,YAC8B;AAK9B,QAAO;EACN,OAAO;EACP,QAAQ,kCANM,MAAM,WAAW,gCAAgC;GAC/D,WAAW;GACX,WAAW;GACX,CAAC,CAGgD;EACjD;;AAGF,SAAS,wBAAwB,OAAoD;CACpF,MAAM,YACL,MAAM,QAAQ,MAAM,EAAE,aAAa,OAAO,kBAAkB,gBAAgB,IAC5E,MAAM,QAAQ,MAAM,EAAE,aAAa,OAAO,kBAAkB,UAAU;AACvE,KAAI,CAAC,UACJ,OAAM,IAAI,MAAM,4CAA4C;AAG7D,QAAO;EACN,YAAY,MAAM;EAClB,WAAW,MAAM;EACjB,OAAO,UAAU,OAAO;EACxB,MAAM,UAAU,OAAO;EACvB,QAAQ,UAAU,OAAO;EACzB,QAAQ,UAAU,OAAO;EACzB,aAAa,UAAU,OAAO;EAC9B,WAAW,MAAM;EACjB,SAAS,MAAM,QAAQ,SAAS,EAAE,QAAQ,kBAAkB;AAC3D,OAAI,OAAO,kBAAkB,aAAa,OAAO,kBAAkB,gBAClE,QAAO,EAAE;AAEV,UAAO,CACN;IACC,SAAS,OAAO;IAChB,aAAa,YAAY,KAAK,gBAAgB;KAC7C,WAAW,WAAW;KACtB,WAAW,WAAW;KACtB,iBAAiB,WAAW;KAC5B,eAAe,iCAAiC,WAAW,cAAc;KACzE,EAAE;IACH,CACD;IACA;EACF;;AAGF,SAAS,iCACR,eAC8C;AAC9C,KACC,kBAAkB,iBAClB,kBAAkB,gBAClB,kBAAkB,sBAElB,QAAO;AAER,QAAO"}
|
|
1
|
+
{"version":3,"file":"media-usage-DPQ3K4xB.mjs","names":[],"sources":["../src/media/usage/content-repair.ts","../src/api/handlers/media-usage.ts"],"sourcesContent":["import { sql, type Kysely } from \"kysely\";\nimport { ulid } from \"ulidx\";\n\nimport {\n\tMediaUsageRepository,\n\ttype MediaUsageSource,\n} from \"../../database/repositories/media-usage.js\";\nimport type { Database } from \"../../database/types.js\";\nimport { validateIdentifier } from \"../../database/validate.js\";\nimport { chunks, SQL_BATCH_SIZE } from \"../../utils/chunks.js\";\nimport {\n\tloadContentMediaUsageFields,\n\tMediaUsageFieldDiscoveryError,\n\ttype ContentMediaUsageFieldDiscovery,\n} from \"./content-fields.js\";\nimport {\n\tCONTENT_MEDIA_USAGE_ADAPTER_ID,\n\tCONTENT_MEDIA_USAGE_COLLECTION_SCOPE,\n\twithContentUsageCollectionLock,\n} from \"./content-refresh.js\";\nimport {\n\tCONTENT_SOURCE_SCHEMA_VERSION,\n\ttype ContentMediaUsageSnapshot,\n\tloadContentMediaUsageSnapshots,\n} from \"./content-snapshots.js\";\nimport {\n\tbuildContentMediaUsageSourceKey,\n\tMEDIA_USAGE_CONTENT_SOURCE_VARIANTS,\n} from \"./source-key.js\";\n\nexport type ContentMediaUsageRepairStatus = \"complete\" | \"partial\" | \"failed\" | \"stale\";\n\nexport const CONTENT_MEDIA_USAGE_REPAIR_ERROR = {\n\tCOLLECTION_NOT_FOUND: \"COLLECTION_NOT_FOUND\",\n\tCONTENT_NOT_FOUND: \"CONTENT_NOT_FOUND\",\n\tDRAFT_REVISION_NOT_FOUND: \"DRAFT_REVISION_NOT_FOUND\",\n\tDRAFT_REVISION_MISMATCH: \"DRAFT_REVISION_MISMATCH\",\n\tDRAFT_REVISION_INVALID: \"DRAFT_REVISION_INVALID\",\n\tCONTENT_USAGE_REPAIR_ERROR: \"CONTENT_USAGE_REPAIR_ERROR\",\n\tCONTENT_USAGE_REPAIR_CONFLICT: \"CONTENT_USAGE_REPAIR_CONFLICT\",\n\tINVALID_REPEATER_VALIDATION: \"INVALID_REPEATER_VALIDATION\",\n} as const;\n\nexport type ContentMediaUsageRepairErrorCode =\n\t(typeof CONTENT_MEDIA_USAGE_REPAIR_ERROR)[keyof typeof CONTENT_MEDIA_USAGE_REPAIR_ERROR];\n\nexport interface ContentMediaUsageRepairCollectionInput {\n\tcollectionSlug: string;\n}\n\nexport interface ContentMediaUsageRepairScope {\n\tadapterId: typeof CONTENT_MEDIA_USAGE_ADAPTER_ID;\n\tscopeType: typeof CONTENT_MEDIA_USAGE_COLLECTION_SCOPE;\n\tscopeKey: string;\n}\n\nexport interface ContentMediaUsageRepairCollectionResult {\n\tscope: ContentMediaUsageRepairScope;\n\tstatus: ContentMediaUsageRepairStatus;\n\tindexedSourceCount: number;\n\tfailedSourceCount: number;\n\tskippedSourceCount: number;\n\tdeletedSourceCount: number;\n\tlastErrorCode: string | null;\n\tstartedAt: string;\n\tcompletedAt: string | null;\n}\n\nexport interface ContentMediaUsageRepairAllResult {\n\tstatus: ContentMediaUsageRepairStatus;\n\tcollections: ContentMediaUsageRepairCollectionResult[];\n\tindexedSourceCount: number;\n\tfailedSourceCount: number;\n\tskippedSourceCount: number;\n\tdeletedSourceCount: number;\n}\n\nexport interface ContentMediaUsageCollectionScan {\n\tcollectionSlug: string;\n\tcontentIds: string[];\n}\n\ninterface ContentMediaUsageCollectionRecord {\n\tid: string;\n\tslug: string;\n}\n\ninterface ContentMediaUsageInitialCollectionResult {\n\tcollection: ContentMediaUsageCollectionRecord;\n\tresult: ContentMediaUsageRepairCollectionResult;\n}\n\nexport async function repairContentMediaUsageAll(\n\tdb: Kysely<Database>,\n): Promise<ContentMediaUsageRepairAllResult> {\n\tconst collections = await loadContentMediaUsageCollectionRecords(db);\n\tconst results: ContentMediaUsageInitialCollectionResult[] = [];\n\n\tfor (const collection of collections) {\n\t\tresults.push({\n\t\t\tcollection,\n\t\t\tresult: await repairContentMediaUsageCollectionSafely(db, collection.slug),\n\t\t});\n\t}\n\n\treturn aggregateContentMediaUsageRepairAll(\n\t\tawait filterExistingContentMediaUsageCollectionResults(db, results),\n\t);\n}\n\nexport async function scanContentMediaUsageCollection(\n\tdb: Kysely<Database>,\n\tcollectionSlug: string,\n): Promise<ContentMediaUsageCollectionScan | null> {\n\tvalidateIdentifier(collectionSlug, \"collection slug\");\n\tconst collection = await db\n\t\t.selectFrom(\"_emdash_collections\")\n\t\t.select(\"id\")\n\t\t.where(\"slug\", \"=\", collectionSlug)\n\t\t.executeTakeFirst();\n\tif (!collection) return null;\n\n\tconst tableName = getContentTableName(collectionSlug);\n\tconst rows = await sql<{ id: string }>`\n\t\tSELECT id\n\t\tFROM ${sql.ref(tableName)}\n\t\tORDER BY id ASC\n\t`.execute(db);\n\n\treturn {\n\t\tcollectionSlug,\n\t\tcontentIds: rows.rows.map((row) => row.id),\n\t};\n}\n\nexport async function repairContentMediaUsageCollection(\n\tdb: Kysely<Database>,\n\tinput: ContentMediaUsageRepairCollectionInput,\n): Promise<ContentMediaUsageRepairCollectionResult> {\n\tvalidateIdentifier(input.collectionSlug, \"collection slug\");\n\treturn withContentUsageCollectionLock(input.collectionSlug, () =>\n\t\trepairContentMediaUsageCollectionUnlocked(db, input.collectionSlug),\n\t);\n}\n\nasync function loadContentMediaUsageCollectionRecords(\n\tdb: Kysely<Database>,\n): Promise<ContentMediaUsageCollectionRecord[]> {\n\treturn db\n\t\t.selectFrom(\"_emdash_collections\")\n\t\t.select([\"id\", \"slug\"])\n\t\t.orderBy(\"slug\", \"asc\")\n\t\t.execute();\n}\n\nasync function repairContentMediaUsageCollectionSafely(\n\tdb: Kysely<Database>,\n\tcollectionSlug: string,\n): Promise<ContentMediaUsageRepairCollectionResult> {\n\ttry {\n\t\treturn await repairContentMediaUsageCollection(db, { collectionSlug });\n\t} catch (error) {\n\t\tconsole.error(`[media-usage] Failed to repair collection ${collectionSlug}:`, error);\n\t\tconst now = new Date().toISOString();\n\t\treturn {\n\t\t\tscope: contentMediaUsageCollectionScope(collectionSlug),\n\t\t\tstatus: \"failed\",\n\t\t\tindexedSourceCount: 0,\n\t\t\tfailedSourceCount: 0,\n\t\t\tskippedSourceCount: 0,\n\t\t\tdeletedSourceCount: 0,\n\t\t\tlastErrorCode: CONTENT_MEDIA_USAGE_REPAIR_ERROR.CONTENT_USAGE_REPAIR_ERROR,\n\t\t\tstartedAt: now,\n\t\t\tcompletedAt: now,\n\t\t};\n\t}\n}\n\nasync function filterExistingContentMediaUsageCollectionResults(\n\tdb: Kysely<Database>,\n\tresults: readonly ContentMediaUsageInitialCollectionResult[],\n): Promise<ContentMediaUsageRepairCollectionResult[]> {\n\tconst currentCollections = await loadContentMediaUsageCollectionRecordsSafely(db);\n\tconst currentIdsBySlug = new Map(\n\t\tcurrentCollections.map((collection) => [collection.slug, collection.id]),\n\t);\n\tconst includedResults: ContentMediaUsageRepairCollectionResult[] = [];\n\tconst excludedResults: ContentMediaUsageRepairCollectionResult[] = [];\n\n\tfor (const { collection, result } of results) {\n\t\tif (currentIdsBySlug.get(collection.slug) === collection.id) {\n\t\t\tincludedResults.push(result);\n\t\t} else {\n\t\t\texcludedResults.push(result);\n\t\t}\n\t}\n\n\tif (excludedResults.length > 0) {\n\t\tconst repo = new MediaUsageRepository(db);\n\t\tfor (const result of excludedResults) {\n\t\t\tawait repo.deleteIndexStatus(result.scope);\n\t\t}\n\t}\n\n\treturn includedResults;\n}\n\nasync function loadContentMediaUsageCollectionRecordsSafely(\n\tdb: Kysely<Database>,\n): Promise<ContentMediaUsageCollectionRecord[]> {\n\ttry {\n\t\treturn await loadContentMediaUsageCollectionRecords(db);\n\t} catch {\n\t\t// Retry once before failing; returning unpruned results can over-report deleted collections.\n\t}\n\n\ttry {\n\t\treturn await loadContentMediaUsageCollectionRecords(db);\n\t} catch (error) {\n\t\tconsole.error(\"[media-usage] Failed to reconcile all-content repair collections:\", error);\n\t\tthrow error;\n\t}\n}\n\nfunction aggregateContentMediaUsageRepairAll(\n\tcollections: readonly ContentMediaUsageRepairCollectionResult[],\n): ContentMediaUsageRepairAllResult {\n\treturn {\n\t\tstatus: determineRepairAllStatus(collections),\n\t\tcollections: [...collections],\n\t\tindexedSourceCount: sumCollectionRepairCount(collections, \"indexedSourceCount\"),\n\t\tfailedSourceCount: sumCollectionRepairCount(collections, \"failedSourceCount\"),\n\t\tskippedSourceCount: sumCollectionRepairCount(collections, \"skippedSourceCount\"),\n\t\tdeletedSourceCount: sumCollectionRepairCount(collections, \"deletedSourceCount\"),\n\t};\n}\n\nfunction determineRepairAllStatus(\n\tcollections: readonly ContentMediaUsageRepairCollectionResult[],\n): ContentMediaUsageRepairStatus {\n\tif (collections.length === 0) return \"complete\";\n\tif (collections.every((collection) => collection.status === \"complete\")) return \"complete\";\n\tif (collections.some((collection) => collection.status === \"stale\")) return \"stale\";\n\tif (collections.some((collection) => collection.status === \"partial\")) return \"partial\";\n\tif (collections.every((collection) => collection.status === \"failed\")) return \"failed\";\n\treturn \"partial\";\n}\n\nfunction sumCollectionRepairCount(\n\tcollections: readonly ContentMediaUsageRepairCollectionResult[],\n\tkey: \"indexedSourceCount\" | \"failedSourceCount\" | \"skippedSourceCount\" | \"deletedSourceCount\",\n): number {\n\treturn collections.reduce((sum, collection) => sum + collection[key], 0);\n}\n\nasync function repairContentMediaUsageCollectionUnlocked(\n\tdb: Kysely<Database>,\n\tcollectionSlug: string,\n): Promise<ContentMediaUsageRepairCollectionResult> {\n\tconst startedAt = new Date().toISOString();\n\tconst scope = contentMediaUsageCollectionScope(collectionSlug);\n\tif (!(await contentCollectionExists(db, collectionSlug))) {\n\t\treturn {\n\t\t\tscope,\n\t\t\tstatus: \"failed\",\n\t\t\tindexedSourceCount: 0,\n\t\t\tfailedSourceCount: 0,\n\t\t\tskippedSourceCount: 0,\n\t\t\tdeletedSourceCount: 0,\n\t\t\tlastErrorCode: CONTENT_MEDIA_USAGE_REPAIR_ERROR.COLLECTION_NOT_FOUND,\n\t\t\tstartedAt,\n\t\t\tcompletedAt: startedAt,\n\t\t};\n\t}\n\n\tconst repo = new MediaUsageRepository(db);\n\tconst runToken = ulid();\n\tawait repo.beginIndexStatusRepair({\n\t\t...scope,\n\t\trunToken,\n\t\tschemaVersion: CONTENT_SOURCE_SCHEMA_VERSION,\n\t\tstartedAt,\n\t});\n\n\ttry {\n\t\tconst scan = await scanContentMediaUsageCollection(db, collectionSlug);\n\t\tif (!scan) {\n\t\t\tconst completedAt = new Date().toISOString();\n\t\t\treturn await finalizeRepairStatus(repo, {\n\t\t\t\t...scope,\n\t\t\t\trunToken,\n\t\t\t\tcounts: {\n\t\t\t\t\tindexedSourceCount: 0,\n\t\t\t\t\tfailedSourceCount: 0,\n\t\t\t\t\tskippedSourceCount: 0,\n\t\t\t\t\tdeletedSourceCount: 0,\n\t\t\t\t\tlastErrorCode: CONTENT_MEDIA_USAGE_REPAIR_ERROR.COLLECTION_NOT_FOUND,\n\t\t\t\t\tmissingContentIds: new Set(),\n\t\t\t\t},\n\t\t\t\tstatus: \"failed\",\n\t\t\t\tstartedAt,\n\t\t\t\tcompletedAt,\n\t\t\t});\n\t\t}\n\t\tconst counts = await repairScannedContentSources(db, repo, scan);\n\t\tconst finalScan = await scanContentMediaUsageCollection(db, collectionSlug);\n\t\tif (!finalScan) {\n\t\t\tcounts.failedSourceCount++;\n\t\t\tcounts.lastErrorCode = CONTENT_MEDIA_USAGE_REPAIR_ERROR.COLLECTION_NOT_FOUND;\n\t\t} else if (!sameContentIds(repairedContentIds(scan.contentIds, counts), finalScan.contentIds)) {\n\t\t\tmarkRepairConflict(counts);\n\t\t}\n\t\tconst completedAt = new Date().toISOString();\n\t\tconst status = determineRepairStatus(counts);\n\t\treturn await finalizeRepairStatus(repo, {\n\t\t\t...scope,\n\t\t\trunToken,\n\t\t\tcounts,\n\t\t\tstatus,\n\t\t\tstartedAt,\n\t\t\tcompletedAt,\n\t\t});\n\t} catch (error) {\n\t\tif (!(error instanceof MediaUsageFieldDiscoveryError)) {\n\t\t\tconsole.error(`[media-usage] Failed to repair collection ${collectionSlug}:`, error);\n\t\t}\n\t\tconst completedAt = new Date().toISOString();\n\t\tconst lastErrorCode =\n\t\t\terror instanceof MediaUsageFieldDiscoveryError\n\t\t\t\t? error.code\n\t\t\t\t: CONTENT_MEDIA_USAGE_REPAIR_ERROR.CONTENT_USAGE_REPAIR_ERROR;\n\t\treturn finalizeRepairStatus(repo, {\n\t\t\t...scope,\n\t\t\trunToken,\n\t\t\tcounts: {\n\t\t\t\tindexedSourceCount: 0,\n\t\t\t\tfailedSourceCount: 0,\n\t\t\t\tskippedSourceCount: 0,\n\t\t\t\tdeletedSourceCount: 0,\n\t\t\t\tlastErrorCode,\n\t\t\t\tmissingContentIds: new Set(),\n\t\t\t},\n\t\t\tstatus: \"failed\",\n\t\t\tstartedAt,\n\t\t\tcompletedAt,\n\t\t});\n\t}\n}\n\ninterface RepairCounts {\n\tindexedSourceCount: number;\n\tfailedSourceCount: number;\n\tskippedSourceCount: number;\n\tdeletedSourceCount: number;\n\tlastErrorCode: ContentMediaUsageRepairErrorCode | null;\n\tmissingContentIds: Set<string>;\n}\n\nasync function repairScannedContentSources(\n\tdb: Kysely<Database>,\n\trepo: MediaUsageRepository,\n\tscan: ContentMediaUsageCollectionScan,\n): Promise<RepairCounts> {\n\tconst counts: RepairCounts = {\n\t\tindexedSourceCount: 0,\n\t\tfailedSourceCount: 0,\n\t\tskippedSourceCount: 0,\n\t\tdeletedSourceCount: 0,\n\t\tlastErrorCode: null,\n\t\tmissingContentIds: new Set(),\n\t};\n\n\tconst fieldDiscovery = await loadContentMediaUsageFields(db, scan.collectionSlug);\n\tconst observedSources = await repo.findSources(buildContentSourceKeysForScan(scan));\n\n\tfor (const contentId of scan.contentIds) {\n\t\tawait repairContentSource(\n\t\t\tdb,\n\t\t\trepo,\n\t\t\tscan.collectionSlug,\n\t\t\tcontentId,\n\t\t\tfieldDiscovery,\n\t\t\tobservedSources,\n\t\t\tcounts,\n\t\t);\n\t}\n\n\tawait reconcileOrphanedContentSources(db, repo, scan.collectionSlug, counts);\n\treturn counts;\n}\n\nasync function repairContentSource(\n\tdb: Kysely<Database>,\n\trepo: MediaUsageRepository,\n\tcollectionSlug: string,\n\tcontentId: string,\n\tfieldDiscovery: ContentMediaUsageFieldDiscovery,\n\tobservedSources: Map<string, MediaUsageSource>,\n\tcounts: RepairCounts,\n): Promise<void> {\n\tconst sourceKeys = buildContentSourceKeys(collectionSlug, contentId);\n\tconst snapshotsResult = await loadContentMediaUsageSnapshots(\n\t\tdb,\n\t\tcollectionSlug,\n\t\tcontentId,\n\t\tfieldDiscovery,\n\t);\n\tif (!snapshotsResult.success) {\n\t\tif (snapshotsResult.error === CONTENT_MEDIA_USAGE_REPAIR_ERROR.CONTENT_NOT_FOUND) {\n\t\t\tmarkRepairConflict(counts);\n\t\t\tcounts.missingContentIds.add(contentId);\n\t\t\treturn;\n\t\t}\n\t\tcounts.lastErrorCode = snapshotsResult.error;\n\t\tif (snapshotsResult.snapshots) {\n\t\t\t// Partial snapshot failures keep absent variants in place; the attempted source is marked below.\n\t\t\tawait repairSnapshotSources(repo, snapshotsResult.snapshots, observedSources, counts);\n\t\t}\n\t\tif (snapshotsResult.source) {\n\t\t\tconst result = await repo.markSourceAttemptedIfMatching(\n\t\t\t\t{\n\t\t\t\t\t...snapshotsResult.source,\n\t\t\t\t\tsourceCompleteness: \"failed\",\n\t\t\t\t\tlastErrorCode: snapshotsResult.error,\n\t\t\t\t},\n\t\t\t\tobservedSources.get(snapshotsResult.source.sourceKey) ?? null,\n\t\t\t);\n\t\t\tif (result.attempted) {\n\t\t\t\tcounts.failedSourceCount++;\n\t\t\t} else {\n\t\t\t\tmarkRepairConflict(counts);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tcounts.failedSourceCount++;\n\t\treturn;\n\t}\n\n\tconst expectedSourceKeys = await repairSnapshotSources(\n\t\trepo,\n\t\tsnapshotsResult.snapshots,\n\t\tobservedSources,\n\t\tcounts,\n\t);\n\n\tfor (const sourceKey of sourceKeys) {\n\t\tif (expectedSourceKeys.has(sourceKey)) continue;\n\t\tconst observedSource = observedSources.get(sourceKey);\n\t\tif (!observedSource) continue;\n\t\tawait deleteObservedSource(repo, sourceKey, observedSource, counts);\n\t}\n}\n\nasync function repairSnapshotSources(\n\trepo: MediaUsageRepository,\n\tsnapshots: readonly ContentMediaUsageSnapshot[],\n\tobservedSources: Map<string, MediaUsageSource>,\n\tcounts: RepairCounts,\n): Promise<Set<string>> {\n\tconst expectedSourceKeys = new Set<string>();\n\tfor (const snapshot of snapshots) {\n\t\texpectedSourceKeys.add(snapshot.source.sourceKey);\n\t\tconst result = await repo.replaceSourceIfMatching(\n\t\t\tsnapshot.source,\n\t\t\tsnapshot.occurrences,\n\t\t\tobservedSources.get(snapshot.source.sourceKey) ?? null,\n\t\t);\n\t\tif (result.replaced) {\n\t\t\tcounts.indexedSourceCount++;\n\t\t} else {\n\t\t\tmarkRepairConflict(counts);\n\t\t}\n\t}\n\treturn expectedSourceKeys;\n}\n\nfunction markRepairConflict(counts: RepairCounts): void {\n\tcounts.skippedSourceCount++;\n\tcounts.lastErrorCode ??= CONTENT_MEDIA_USAGE_REPAIR_ERROR.CONTENT_USAGE_REPAIR_CONFLICT;\n}\n\nasync function reconcileOrphanedContentSources(\n\tdb: Kysely<Database>,\n\trepo: MediaUsageRepository,\n\tcollectionSlug: string,\n\tcounts: RepairCounts,\n): Promise<void> {\n\tconst sources = await repo.findCollectionContentSources(collectionSlug);\n\tconst existingContentIds = await findExistingContentIds(\n\t\tdb,\n\t\tcollectionSlug,\n\t\tsources.flatMap((source) => (source.contentId ? [source.contentId] : [])),\n\t);\n\n\tfor (const source of sources) {\n\t\tif (!source.contentId) {\n\t\t\tawait deleteObservedSource(repo, source.sourceKey, source, counts);\n\t\t\tcontinue;\n\t\t}\n\t\tif (existingContentIds.has(source.contentId)) continue;\n\t\tawait deleteObservedSourceIfContentAbsent(repo, collectionSlug, source, counts);\n\t}\n}\n\nasync function findExistingContentIds(\n\tdb: Kysely<Database>,\n\tcollectionSlug: string,\n\tcontentIds: readonly string[],\n): Promise<Set<string>> {\n\tvalidateIdentifier(collectionSlug, \"collection slug\");\n\tconst existingContentIds = new Set<string>();\n\tconst uniqueContentIds = [...new Set(contentIds)];\n\tif (uniqueContentIds.length === 0) return existingContentIds;\n\n\tconst tableName = getContentTableName(collectionSlug);\n\tfor (const contentIdBatch of chunks(uniqueContentIds, SQL_BATCH_SIZE)) {\n\t\tconst result = await sql<{ id: string }>`\n\t\t\tSELECT id\n\t\t\tFROM ${sql.ref(tableName)}\n\t\t\tWHERE id IN (${sql.join(contentIdBatch)})\n\t\t`.execute(db);\n\t\tfor (const row of result.rows) {\n\t\t\texistingContentIds.add(row.id);\n\t\t}\n\t}\n\n\treturn existingContentIds;\n}\n\nasync function deleteObservedSourceIfContentAbsent(\n\trepo: MediaUsageRepository,\n\tcollectionSlug: string,\n\tobservedSource: MediaUsageSource,\n\tcounts: RepairCounts,\n): Promise<void> {\n\tif (!observedSource.contentId) return;\n\tconst result = await repo.deleteSourceIfMatchingContentAbsent(\n\t\tobservedSource.sourceKey,\n\t\tobservedSource,\n\t\tcollectionSlug,\n\t\tobservedSource.contentId,\n\t);\n\tif (result.deleted) {\n\t\tcounts.deletedSourceCount++;\n\t\treturn;\n\t}\n\tif (result.contentPresent) return;\n\tif (result.source) {\n\t\tmarkRepairConflict(counts);\n\t}\n}\n\nasync function deleteObservedSource(\n\trepo: MediaUsageRepository,\n\tsourceKey: string,\n\tobservedSource: MediaUsageSource,\n\tcounts: RepairCounts,\n): Promise<void> {\n\tconst result = await repo.deleteSourceIfMatching(sourceKey, observedSource);\n\tif (result.deleted) {\n\t\tcounts.deletedSourceCount++;\n\t\treturn;\n\t}\n\tif (result.source) {\n\t\tmarkRepairConflict(counts);\n\t}\n}\n\ninterface FinalizeInput extends ContentMediaUsageRepairScope {\n\trunToken: string;\n\tcounts: RepairCounts;\n\tstatus: Exclude<ContentMediaUsageRepairStatus, \"stale\">;\n\tstartedAt: string;\n\tcompletedAt: string;\n}\n\nasync function finalizeRepairStatus(\n\trepo: MediaUsageRepository,\n\tinput: FinalizeInput,\n): Promise<ContentMediaUsageRepairCollectionResult> {\n\tconst result = await repo.finalizeIndexStatusRepairIfRunning({\n\t\tadapterId: input.adapterId,\n\t\tscopeType: input.scopeType,\n\t\tscopeKey: input.scopeKey,\n\t\trunToken: input.runToken,\n\t\tstatus: input.status,\n\t\tschemaVersion: CONTENT_SOURCE_SCHEMA_VERSION,\n\t\tcompletedAt: input.completedAt,\n\t\tindexedSourceCount: input.counts.indexedSourceCount,\n\t\tfailedSourceCount: input.counts.failedSourceCount,\n\t\tlastErrorCode: input.counts.lastErrorCode,\n\t});\n\n\treturn {\n\t\tscope: {\n\t\t\tadapterId: input.adapterId,\n\t\t\tscopeType: input.scopeType,\n\t\t\tscopeKey: input.scopeKey,\n\t\t},\n\t\tstatus: result.finalized ? input.status : \"stale\",\n\t\tindexedSourceCount: input.counts.indexedSourceCount,\n\t\tfailedSourceCount: input.counts.failedSourceCount,\n\t\tskippedSourceCount: input.counts.skippedSourceCount,\n\t\tdeletedSourceCount: input.counts.deletedSourceCount,\n\t\tlastErrorCode: result.finalized\n\t\t\t? input.counts.lastErrorCode\n\t\t\t: (result.status?.lastErrorCode ??\n\t\t\t\tCONTENT_MEDIA_USAGE_REPAIR_ERROR.CONTENT_USAGE_REPAIR_CONFLICT),\n\t\tstartedAt: input.startedAt,\n\t\tcompletedAt: result.finalized ? input.completedAt : null,\n\t};\n}\n\nfunction determineRepairStatus(\n\tcounts: RepairCounts,\n): Exclude<ContentMediaUsageRepairStatus, \"stale\"> {\n\tif (counts.failedSourceCount === 0 && counts.skippedSourceCount === 0) return \"complete\";\n\tconst trustedProgress = counts.indexedSourceCount + counts.deletedSourceCount;\n\tif (counts.failedSourceCount > 0 && trustedProgress === 0) {\n\t\treturn \"failed\";\n\t}\n\treturn \"partial\";\n}\n\nfunction buildContentSourceKeys(collectionSlug: string, contentId: string): string[] {\n\treturn MEDIA_USAGE_CONTENT_SOURCE_VARIANTS.map((sourceVariant) =>\n\t\tbuildContentMediaUsageSourceKey({ collectionSlug, contentId, sourceVariant }),\n\t);\n}\n\nfunction buildContentSourceKeysForScan(scan: ContentMediaUsageCollectionScan): string[] {\n\treturn scan.contentIds.flatMap((contentId) =>\n\t\tbuildContentSourceKeys(scan.collectionSlug, contentId),\n\t);\n}\n\nasync function contentCollectionExists(\n\tdb: Kysely<Database>,\n\tcollectionSlug: string,\n): Promise<boolean> {\n\tconst row = await db\n\t\t.selectFrom(\"_emdash_collections\")\n\t\t.select(\"id\")\n\t\t.where(\"slug\", \"=\", collectionSlug)\n\t\t.executeTakeFirst();\n\treturn row !== undefined;\n}\n\nfunction sameContentIds(left: readonly string[], right: readonly string[]): boolean {\n\tif (left.length !== right.length) return false;\n\tconst rightIds = new Set(right);\n\treturn left.every((id) => rightIds.has(id));\n}\n\nfunction repairedContentIds(\n\tcontentIds: readonly string[],\n\tcounts: Pick<RepairCounts, \"missingContentIds\">,\n): string[] {\n\tif (counts.missingContentIds.size === 0) return [...contentIds];\n\treturn contentIds.filter((contentId) => !counts.missingContentIds.has(contentId));\n}\n\nfunction contentMediaUsageCollectionScope(collectionSlug: string): ContentMediaUsageRepairScope {\n\treturn {\n\t\tadapterId: CONTENT_MEDIA_USAGE_ADAPTER_ID,\n\t\tscopeType: CONTENT_MEDIA_USAGE_COLLECTION_SCOPE,\n\t\tscopeKey: collectionSlug,\n\t};\n}\n\nfunction getContentTableName(collectionSlug: string): string {\n\tvalidateIdentifier(collectionSlug, \"collection slug\");\n\treturn `ec_${collectionSlug}`;\n}\n","import type { Kysely } from \"kysely\";\n\nimport {\n\tMediaUsageRepository,\n\ttype MediaUsageCollectionIndexStatusScope,\n\ttype MediaUsageEntryGroup,\n} from \"../../database/repositories/media-usage.js\";\nimport { MediaRepository } from \"../../database/repositories/media.js\";\nimport { InvalidCursorError } from \"../../database/repositories/types.js\";\nimport type { Database } from \"../../database/types.js\";\nimport {\n\tCONTENT_MEDIA_USAGE_ADAPTER_ID,\n\tCONTENT_MEDIA_USAGE_COLLECTION_SCOPE,\n} from \"../../media/usage/content-refresh.js\";\nimport {\n\trepairContentMediaUsageAll,\n\trepairContentMediaUsageCollection,\n\ttype ContentMediaUsageRepairAllResult,\n\ttype ContentMediaUsageRepairCollectionResult,\n} from \"../../media/usage/content-repair.js\";\nimport { CONTENT_SOURCE_SCHEMA_VERSION } from \"../../media/usage/content-snapshots.js\";\nimport { ErrorCode } from \"../errors.js\";\nimport type {\n\tMediaUsageCoverage,\n\tMediaUsageCoverageStatus,\n\tMediaUsageDetailsResponse,\n\tMediaUsageEntryDetail,\n\tMediaUsageOccurrenceDetail,\n\tMediaUsageRepairRequest,\n\tMediaUsageRepairResponse,\n\tMediaUsageSummary,\n} from \"../schemas/media-usage.js\";\nimport type { ApiResult } from \"../types.js\";\n\nexport type {\n\tMediaUsageCoverage,\n\tMediaUsageCoverageStatus,\n\tMediaUsageDetailsResponse,\n\tMediaUsageEntryDetail,\n\tMediaUsageOccurrenceDetail,\n\tMediaUsageSourceDetail,\n\tMediaUsageRepairRequest,\n\tMediaUsageRepairResponse,\n\tMediaUsageSummary,\n} from \"../schemas/media-usage.js\";\n\ntype ContentMediaUsageRepairResult =\n\t| ContentMediaUsageRepairCollectionResult\n\t| ContentMediaUsageRepairAllResult;\n\nexport function aggregateMediaUsageCoverageStatus(\n\tscopes: readonly MediaUsageCollectionIndexStatusScope[],\n): MediaUsageCoverageStatus {\n\tconst statuses = scopes.map(normalizeMediaUsageCoverageStatus);\n\tif (statuses.every((status) => status === \"complete\")) {\n\t\treturn \"complete\";\n\t}\n\tif (statuses.includes(\"unknown\")) return \"unknown\";\n\tif (statuses.includes(\"running\")) return \"running\";\n\tif (statuses.includes(\"stale\")) return \"stale\";\n\tif (statuses.includes(\"partial\")) return \"partial\";\n\tif (statuses.every((status) => status === \"never\")) return \"never\";\n\tif (statuses.every((status) => status === \"failed\")) return \"failed\";\n\treturn \"partial\";\n}\n\nexport async function handleMediaUsageSummaries(\n\tdb: Kysely<Database>,\n\tmediaIds: readonly string[],\n\toptions: { includeCount: boolean },\n): Promise<ApiResult<Record<string, MediaUsageSummary>>> {\n\tif (mediaIds.length === 0) return { success: true, data: {} };\n\n\ttry {\n\t\tconst repository = new MediaUsageRepository(db);\n\t\tconst coverage = await loadMediaUsageCoverage(repository);\n\t\tconst counts = options.includeCount\n\t\t\t? await repository.findActiveEntryCountsByMediaIds(mediaIds)\n\t\t\t: null;\n\t\tconst summaries: Record<string, MediaUsageSummary> = {};\n\n\t\tfor (const mediaId of new Set(mediaIds)) {\n\t\t\tsummaries[mediaId] = {\n\t\t\t\tcount: counts ? (counts.get(mediaId) ?? 0) : null,\n\t\t\t\tcoverage,\n\t\t\t};\n\t\t}\n\n\t\treturn { success: true, data: summaries };\n\t} catch (error) {\n\t\tconsole.error(\"[media-usage] summary read failed:\", error);\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: {\n\t\t\t\tcode: ErrorCode.MEDIA_USAGE_READ_ERROR,\n\t\t\t\tmessage: \"Failed to read media usage\",\n\t\t\t},\n\t\t};\n\t}\n}\n\nexport async function handleMediaUsageDetails(\n\tdb: Kysely<Database>,\n\tmediaId: string,\n\toptions: { cursor?: string; limit?: number },\n): Promise<ApiResult<MediaUsageDetailsResponse>> {\n\ttry {\n\t\tconst media = await new MediaRepository(db).findById(mediaId);\n\t\tif (!media) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: {\n\t\t\t\t\tcode: ErrorCode.NOT_FOUND,\n\t\t\t\t\tmessage: `Media item not found: ${mediaId}`,\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\tconst repository = new MediaUsageRepository(db);\n\t\tconst coverage = await loadMediaUsageCoverage(repository);\n\t\tconst page = await repository.findCurrentEntryUsagePageByMediaId(mediaId, options);\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tdata: {\n\t\t\t\titems: page.items.map(toMediaUsageEntryDetail),\n\t\t\t\t...(page.nextCursor ? { nextCursor: page.nextCursor } : {}),\n\t\t\t\tcoverage,\n\t\t\t},\n\t\t};\n\t} catch (error) {\n\t\tif (error instanceof InvalidCursorError) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: ErrorCode.INVALID_CURSOR, message: error.message },\n\t\t\t};\n\t\t}\n\t\tconsole.error(\"[media-usage] detail read failed:\", error);\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: {\n\t\t\t\tcode: ErrorCode.MEDIA_USAGE_READ_ERROR,\n\t\t\t\tmessage: \"Failed to read media usage\",\n\t\t\t},\n\t\t};\n\t}\n}\n\nexport async function handleMediaUsageRepair(\n\tdb: Kysely<Database>,\n\tinput: MediaUsageRepairRequest,\n): Promise<ApiResult<MediaUsageRepairResponse>> {\n\ttry {\n\t\tlet result: ContentMediaUsageRepairResult;\n\t\tif (input.scope === \"collection\") {\n\t\t\tresult = await repairContentMediaUsageCollection(db, { collectionSlug: input.collection });\n\t\t} else if (input.scope === \"all\") {\n\t\t\tresult = await repairContentMediaUsageAll(db);\n\t\t} else {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: {\n\t\t\t\t\tcode: ErrorCode.VALIDATION_ERROR,\n\t\t\t\t\tmessage: \"Invalid media usage repair request\",\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\treturn { success: true, data: toMediaUsageRepairResponse(result) };\n\t} catch (error) {\n\t\tconsole.error(\"[media-usage] repair failed:\", error);\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: {\n\t\t\t\tcode: ErrorCode.MEDIA_USAGE_REPAIR_ERROR,\n\t\t\t\tmessage: \"Failed to repair media usage\",\n\t\t\t},\n\t\t};\n\t}\n}\n\nexport function toMediaUsageRepairResponse(\n\tresult: ContentMediaUsageRepairResult,\n): MediaUsageRepairResponse {\n\tconst collections = \"collections\" in result ? result.collections : [result];\n\n\treturn {\n\t\tstatus: result.status,\n\t\tindexedSourceCount: result.indexedSourceCount,\n\t\tfailedSourceCount: result.failedSourceCount,\n\t\tskippedSourceCount: result.skippedSourceCount,\n\t\tdeletedSourceCount: result.deletedSourceCount,\n\t\tcollections: collections.map(toMediaUsageRepairCollectionSummary),\n\t};\n}\n\nfunction toMediaUsageRepairCollectionSummary(result: ContentMediaUsageRepairCollectionResult) {\n\treturn {\n\t\tcollection: result.scope.scopeKey,\n\t\tstatus: result.status,\n\t\tindexedSourceCount: result.indexedSourceCount,\n\t\tfailedSourceCount: result.failedSourceCount,\n\t\tskippedSourceCount: result.skippedSourceCount,\n\t\tdeletedSourceCount: result.deletedSourceCount,\n\t\tlastErrorCode: result.lastErrorCode,\n\t\tstartedAt: result.startedAt,\n\t\tcompletedAt: result.completedAt,\n\t};\n}\n\nfunction normalizeMediaUsageCoverageStatus(\n\tscope: MediaUsageCollectionIndexStatusScope,\n): MediaUsageCoverageStatus {\n\tif (scope.status === null) return \"never\";\n\tif (scope.status === \"complete\") {\n\t\treturn scope.schemaVersion === CONTENT_SOURCE_SCHEMA_VERSION ? \"complete\" : \"stale\";\n\t}\n\tif (\n\t\tscope.status === \"never\" ||\n\t\tscope.status === \"running\" ||\n\t\tscope.status === \"partial\" ||\n\t\tscope.status === \"failed\" ||\n\t\tscope.status === \"stale\"\n\t) {\n\t\treturn scope.status;\n\t}\n\treturn \"unknown\";\n}\n\nasync function loadMediaUsageCoverage(\n\trepository: MediaUsageRepository,\n): Promise<MediaUsageCoverage> {\n\tconst scopes = await repository.findCollectionIndexStatusScopes({\n\t\tadapterId: CONTENT_MEDIA_USAGE_ADAPTER_ID,\n\t\tscopeType: CONTENT_MEDIA_USAGE_COLLECTION_SCOPE,\n\t});\n\treturn {\n\t\tscope: \"all_content_collections\",\n\t\tstatus: aggregateMediaUsageCoverageStatus(scopes),\n\t};\n}\n\nfunction toMediaUsageEntryDetail(group: MediaUsageEntryGroup): MediaUsageEntryDetail {\n\tconst preferred =\n\t\tgroup.sources.find(({ source }) => source.sourceVariant === \"draft_overlay\") ??\n\t\tgroup.sources.find(({ source }) => source.sourceVariant === \"columns\");\n\tif (!preferred) {\n\t\tthrow new Error(\"Media usage entry has no supported source\");\n\t}\n\n\treturn {\n\t\tcollection: group.collectionSlug,\n\t\tcontentId: group.contentId,\n\t\ttitle: preferred.source.contentTitle,\n\t\tslug: preferred.source.contentSlug,\n\t\tlocale: preferred.source.locale,\n\t\tstatus: preferred.source.contentStatus,\n\t\tscheduledAt: preferred.source.contentScheduledAt,\n\t\tdeletedAt: group.contentDeletedAt,\n\t\tsources: group.sources.flatMap(({ source, occurrences }) => {\n\t\t\tif (source.sourceVariant !== \"columns\" && source.sourceVariant !== \"draft_overlay\") {\n\t\t\t\treturn [];\n\t\t\t}\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\tvariant: source.sourceVariant,\n\t\t\t\t\toccurrences: occurrences.map((occurrence) => ({\n\t\t\t\t\t\tfieldSlug: occurrence.fieldSlug,\n\t\t\t\t\t\tfieldPath: occurrence.fieldPath,\n\t\t\t\t\t\toccurrenceIndex: occurrence.occurrenceIndex,\n\t\t\t\t\t\treferenceType: normalizeMediaUsageReferenceType(occurrence.referenceType),\n\t\t\t\t\t})),\n\t\t\t\t},\n\t\t\t];\n\t\t}),\n\t};\n}\n\nfunction normalizeMediaUsageReferenceType(\n\treferenceType: string,\n): MediaUsageOccurrenceDetail[\"referenceType\"] {\n\tif (\n\t\treferenceType === \"image_field\" ||\n\t\treferenceType === \"file_field\" ||\n\t\treferenceType === \"portable_text_image\"\n\t) {\n\t\treturn referenceType;\n\t}\n\treturn \"unknown\";\n}\n"],"mappings":";;;;;;;;;;;AAgCA,MAAa,mCAAmC;CAC/C,sBAAsB;CACtB,mBAAmB;CACnB,0BAA0B;CAC1B,yBAAyB;CACzB,wBAAwB;CACxB,4BAA4B;CAC5B,+BAA+B;CAC/B,6BAA6B;CAC7B;AAmDD,eAAsB,2BACrB,IAC4C;CAC5C,MAAM,cAAc,MAAM,uCAAuC,GAAG;CACpE,MAAM,UAAsD,EAAE;AAE9D,MAAK,MAAM,cAAc,YACxB,SAAQ,KAAK;EACZ;EACA,QAAQ,MAAM,wCAAwC,IAAI,WAAW,KAAK;EAC1E,CAAC;AAGH,QAAO,oCACN,MAAM,iDAAiD,IAAI,QAAQ,CACnE;;AAGF,eAAsB,gCACrB,IACA,gBACkD;AAClD,oBAAmB,gBAAgB,kBAAkB;AAMrD,KAAI,CALe,M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as getI18nConfig } from "./config-
|
|
1
|
+
import { o as __exportAll } from "./runner-BdeLEgad.mjs";
|
|
2
|
+
import { i as resolveConfiguredLocale, n as getI18nConfig } from "./config-B6b_BobR.mjs";
|
|
3
3
|
import { c as invalidateMenuObjectCache } from "./object-cache-Bok5j2ae.mjs";
|
|
4
4
|
import { t as withTransaction } from "./transaction-D0FOsb3X.mjs";
|
|
5
5
|
import { ulid } from "ulidx";
|
|
@@ -379,7 +379,8 @@ function ambiguousMenuLocaleError(name, locales) {
|
|
|
379
379
|
* this to translate (name, locale) into an unambiguous menu row.
|
|
380
380
|
*/
|
|
381
381
|
async function resolveMenu(repo, name, options) {
|
|
382
|
-
const
|
|
382
|
+
const locale = options.locale ? resolveConfiguredLocale(options.locale) : void 0;
|
|
383
|
+
const matches = await repo.findByName(name, { locale });
|
|
383
384
|
if (matches.length === 0) return {
|
|
384
385
|
success: false,
|
|
385
386
|
error: {
|
|
@@ -401,9 +402,11 @@ async function resolveMenu(repo, name, options) {
|
|
|
401
402
|
*/
|
|
402
403
|
async function handleMenuList(db, options = {}) {
|
|
403
404
|
try {
|
|
405
|
+
const repo = new MenuRepository(db);
|
|
406
|
+
const locale = options.locale ? resolveConfiguredLocale(options.locale) : void 0;
|
|
404
407
|
return {
|
|
405
408
|
success: true,
|
|
406
|
-
data: await
|
|
409
|
+
data: await repo.findMany({ locale })
|
|
407
410
|
};
|
|
408
411
|
} catch {
|
|
409
412
|
return {
|
|
@@ -439,7 +442,7 @@ async function handleMenuCreate(db, input) {
|
|
|
439
442
|
}
|
|
440
443
|
};
|
|
441
444
|
}
|
|
442
|
-
const effectiveLocale = input.locale
|
|
445
|
+
const effectiveLocale = input.locale ? resolveConfiguredLocale(input.locale) : getI18nConfig()?.defaultLocale ?? "en";
|
|
443
446
|
if (await repo.existsByNameAndLocale(input.name, effectiveLocale)) return {
|
|
444
447
|
success: false,
|
|
445
448
|
error: {
|
|
@@ -449,7 +452,10 @@ async function handleMenuCreate(db, input) {
|
|
|
449
452
|
};
|
|
450
453
|
return {
|
|
451
454
|
success: true,
|
|
452
|
-
data: await repo.create(
|
|
455
|
+
data: await repo.create({
|
|
456
|
+
...input,
|
|
457
|
+
locale: effectiveLocale
|
|
458
|
+
})
|
|
453
459
|
};
|
|
454
460
|
} catch {
|
|
455
461
|
return {
|
|
@@ -471,7 +477,8 @@ async function handleMenuCreate(db, input) {
|
|
|
471
477
|
async function handleMenuGet(db, name, options = {}) {
|
|
472
478
|
try {
|
|
473
479
|
const repo = new MenuRepository(db);
|
|
474
|
-
const
|
|
480
|
+
const locale = options.locale ? resolveConfiguredLocale(options.locale) : void 0;
|
|
481
|
+
const matches = await repo.findByName(name, { locale });
|
|
475
482
|
if (matches.length === 0) return {
|
|
476
483
|
success: false,
|
|
477
484
|
error: {
|
|
@@ -734,4 +741,4 @@ async function handleMenuItemReorder(db, menuName, items, options = {}) {
|
|
|
734
741
|
|
|
735
742
|
//#endregion
|
|
736
743
|
export { handleMenuItemDelete as a, handleMenuList as c, menus_exports as d, handleMenuItemCreate as i, handleMenuTranslations as l, handleMenuDelete as n, handleMenuItemReorder as o, handleMenuGet as r, handleMenuItemUpdate as s, handleMenuCreate as t, handleMenuUpdate as u };
|
|
737
|
-
//# sourceMappingURL=menus-
|
|
744
|
+
//# sourceMappingURL=menus-BMGzWyWH.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"menus-BMGzWyWH.mjs","names":[],"sources":["../src/database/repositories/menu.ts","../src/api/handlers/menus.ts"],"sourcesContent":["/**\n * Menu repository\n *\n * Owns every SQL touch for `_emdash_menus` and `_emdash_menu_items`, plus the\n * row→entity mapping. Matches the architecture used by every other resource\n * (content, taxonomies, redirects, comments, media): handlers stay thin and\n * orchestrate; the repository is the single place where snake_case DB columns\n * become camelCase entities (and vice versa).\n *\n * i18n: menus are per-locale. `(name, locale)` is unique. Translations of the\n * same menu share a `translation_group` ULID. Menu item `reference_id` stores\n * the referenced content's translation_group (not a specific row id) so a\n * single menu item survives content translations.\n */\n\nimport type { Kysely, Selectable } from \"kysely\";\nimport { ulid } from \"ulidx\";\n\nimport { invalidateMenuObjectCache } from \"../../object-cache/index.js\";\nimport { withTransaction } from \"../transaction.js\";\nimport type { Database, MenuItemTable, MenuTable } from \"../types.js\";\n\n/**\n * Thrown from inside a repository transaction when the menu the caller\n * resolved earlier has since been deleted. Handlers translate this to a\n * `NOT_FOUND` API response. Necessary because D1 disables FK enforcement\n * (so `ON DELETE CASCADE` won't fire), and an unchecked `setItems` would\n * happily insert items whose `menu_id` no longer exists, leaving orphans.\n */\nexport class MenuGoneError extends Error {\n\tconstructor(public readonly menuId: string) {\n\t\tsuper(`Menu ${menuId} was deleted while being modified`);\n\t\tthis.name = \"MenuGoneError\";\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Entity shapes (camelCase — what the API returns)\n// ---------------------------------------------------------------------------\n\nexport interface Menu {\n\tid: string;\n\tname: string;\n\tlabel: string;\n\tcreatedAt: string;\n\tupdatedAt: string;\n\tlocale: string;\n\ttranslationGroup: string | null;\n}\n\nexport interface MenuItem {\n\tid: string;\n\tmenuId: string;\n\tparentId: string | null;\n\tsortOrder: number;\n\ttype: string;\n\treferenceCollection: string | null;\n\treferenceId: string | null;\n\tcustomUrl: string | null;\n\tlabel: string;\n\ttitleAttr: string | null;\n\ttarget: string | null;\n\tcssClasses: string | null;\n\tcreatedAt: string;\n\tlocale: string;\n\ttranslationGroup: string | null;\n}\n\nexport interface MenuListItem extends Menu {\n\titemCount: number;\n}\n\nexport interface MenuWithItems extends Menu {\n\titems: MenuItem[];\n}\n\nexport interface MenuTranslation {\n\tid: string;\n\tname: string;\n\tlabel: string;\n\tlocale: string;\n\tupdatedAt: string;\n}\n\n// ---------------------------------------------------------------------------\n// Input shapes\n// ---------------------------------------------------------------------------\n\nexport interface CreateMenuInput {\n\tname: string;\n\tlabel: string;\n\tlocale?: string;\n\t/**\n\t * When set, the new menu joins the source menu's translation_group and\n\t * inherits its items (cloned, with new ULIDs but the same translation_group\n\t * per item so nav entries stay logically identified across translations).\n\t */\n\ttranslationOf?: string;\n}\n\nexport interface UpdateMenuInput {\n\tlabel?: string;\n}\n\nexport interface CreateMenuItemInput {\n\ttype: string;\n\tlabel: string;\n\treferenceCollection?: string;\n\treferenceId?: string;\n\tcustomUrl?: string;\n\ttarget?: string;\n\ttitleAttr?: string;\n\tcssClasses?: string;\n\tparentId?: string;\n\tsortOrder?: number;\n}\n\nexport interface UpdateMenuItemInput {\n\tlabel?: string;\n\tcustomUrl?: string;\n\ttarget?: string;\n\ttitleAttr?: string;\n\tcssClasses?: string;\n\tparentId?: string | null;\n\tsortOrder?: number;\n}\n\n/**\n * Item shape used by `setItems()`. Items are placed by array order. Children\n * point at parents via `parentIndex` (must reference an earlier index, so the\n * insert can resolve parents before children). The validation of that ordering\n * lives at the API boundary (`handleMenuSetItems`) so REST/MCP callers receive\n * the same error shape.\n */\nexport interface SetMenuItem {\n\tlabel: string;\n\ttype: \"custom\" | \"page\" | \"post\" | \"taxonomy\" | \"collection\";\n\tcustomUrl?: string;\n\treferenceCollection?: string;\n\treferenceId?: string;\n\ttitleAttr?: string;\n\ttarget?: string;\n\tcssClasses?: string;\n\tparentIndex?: number;\n}\n\nexport interface ReorderItem {\n\tid: string;\n\tparentId: string | null;\n\tsortOrder: number;\n}\n\n// ---------------------------------------------------------------------------\n// Row → entity mappers\n// ---------------------------------------------------------------------------\n\nfunction rowToMenu(row: Selectable<MenuTable>): Menu {\n\treturn {\n\t\tid: row.id,\n\t\tname: row.name,\n\t\tlabel: row.label,\n\t\tcreatedAt: row.created_at,\n\t\tupdatedAt: row.updated_at,\n\t\tlocale: row.locale,\n\t\ttranslationGroup: row.translation_group,\n\t};\n}\n\nfunction rowToMenuItem(row: Selectable<MenuItemTable>): MenuItem {\n\treturn {\n\t\tid: row.id,\n\t\tmenuId: row.menu_id,\n\t\tparentId: row.parent_id,\n\t\tsortOrder: row.sort_order,\n\t\ttype: row.type,\n\t\treferenceCollection: row.reference_collection,\n\t\treferenceId: row.reference_id,\n\t\tcustomUrl: row.custom_url,\n\t\tlabel: row.label,\n\t\ttitleAttr: row.title_attr,\n\t\ttarget: row.target,\n\t\tcssClasses: row.css_classes,\n\t\tcreatedAt: row.created_at,\n\t\tlocale: row.locale,\n\t\ttranslationGroup: row.translation_group,\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// Repository\n// ---------------------------------------------------------------------------\n\nexport class MenuRepository {\n\tconstructor(private db: Kysely<Database>) {}\n\n\t// --- Menus -------------------------------------------------------------\n\n\t/**\n\t * List menus with their item counts. When `locale` is omitted, returns\n\t * every locale variant as its own row (consistent with the admin listing\n\t * model: each translation is its own menu for editing purposes).\n\t */\n\tasync findMany(options: { locale?: string } = {}): Promise<MenuListItem[]> {\n\t\t// Single LEFT JOIN + GROUP BY for the per-menu count. Avoids N+1.\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"_emdash_menus as m\")\n\t\t\t.leftJoin(\"_emdash_menu_items as i\", \"i.menu_id\", \"m.id\")\n\t\t\t.select(({ fn }) => [\n\t\t\t\t\"m.id\",\n\t\t\t\t\"m.name\",\n\t\t\t\t\"m.label\",\n\t\t\t\t\"m.created_at\",\n\t\t\t\t\"m.updated_at\",\n\t\t\t\t\"m.locale\",\n\t\t\t\t\"m.translation_group\",\n\t\t\t\tfn.count<number>(\"i.id\").as(\"itemCount\"),\n\t\t\t])\n\t\t\t.groupBy([\n\t\t\t\t\"m.id\",\n\t\t\t\t\"m.name\",\n\t\t\t\t\"m.label\",\n\t\t\t\t\"m.created_at\",\n\t\t\t\t\"m.updated_at\",\n\t\t\t\t\"m.locale\",\n\t\t\t\t\"m.translation_group\",\n\t\t\t])\n\t\t\t.orderBy(\"m.name\", \"asc\");\n\t\tif (options.locale !== undefined) query = query.where(\"m.locale\", \"=\", options.locale);\n\t\tconst rows = await query.execute();\n\n\t\treturn rows.map((row) => ({\n\t\t\t// Postgres returns count() as `string`; SQLite as `number`. Normalize.\n\t\t\titemCount: typeof row.itemCount === \"string\" ? Number(row.itemCount) : row.itemCount,\n\t\t\t...rowToMenu({\n\t\t\t\tid: row.id,\n\t\t\t\tname: row.name,\n\t\t\t\tlabel: row.label,\n\t\t\t\tcreated_at: row.created_at,\n\t\t\t\tupdated_at: row.updated_at,\n\t\t\t\tlocale: row.locale,\n\t\t\t\ttranslation_group: row.translation_group,\n\t\t\t}),\n\t\t}));\n\t}\n\n\t/**\n\t * Find every menu row matching `name` (one per locale on multi-locale\n\t * installs). Callers use this both to look up a single menu (when locale\n\t * is supplied) and to detect AMBIGUOUS_LOCALE situations (`length > 1`).\n\t */\n\tasync findByName(name: string, options: { locale?: string } = {}): Promise<Menu[]> {\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"_emdash_menus\")\n\t\t\t.selectAll()\n\t\t\t.where(\"name\", \"=\", name)\n\t\t\t.orderBy(\"locale\", \"asc\");\n\t\tif (options.locale !== undefined) query = query.where(\"locale\", \"=\", options.locale);\n\t\tconst rows = await query.execute();\n\t\treturn rows.map(rowToMenu);\n\t}\n\n\tasync findById(id: string): Promise<Menu | null> {\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"_emdash_menus\")\n\t\t\t.selectAll()\n\t\t\t.where(\"id\", \"=\", id)\n\t\t\t.executeTakeFirst();\n\t\treturn row ? rowToMenu(row) : null;\n\t}\n\n\t/** Fetch a menu plus its items, ordered by `sort_order`. */\n\tasync findWithItems(menuId: string): Promise<MenuWithItems | null> {\n\t\tconst menu = await this.findById(menuId);\n\t\tif (!menu) return null;\n\t\tconst items = await this.findItems(menuId);\n\t\treturn { ...menu, items };\n\t}\n\n\tasync findItems(menuId: string): Promise<MenuItem[]> {\n\t\tconst rows = await this.db\n\t\t\t.selectFrom(\"_emdash_menu_items\")\n\t\t\t.selectAll()\n\t\t\t.where(\"menu_id\", \"=\", menuId)\n\t\t\t.orderBy(\"sort_order\", \"asc\")\n\t\t\t.execute();\n\t\treturn rows.map(rowToMenuItem);\n\t}\n\n\t/**\n\t * Returns true when a menu already exists for the given `(name, locale)`.\n\t * Used by the handler to surface a CONFLICT before attempting the insert.\n\t */\n\tasync existsByNameAndLocale(name: string, locale: string): Promise<boolean> {\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"_emdash_menus\")\n\t\t\t.select(\"id\")\n\t\t\t.where(\"name\", \"=\", name)\n\t\t\t.where(\"locale\", \"=\", locale)\n\t\t\t.executeTakeFirst();\n\t\treturn row !== undefined;\n\t}\n\n\t/**\n\t * Create a menu. When `translationOf` is supplied the new menu joins the\n\t * source menu's translation_group and clones its items (each clone gets a\n\t * fresh ULID, but inherits the source item's `translation_group` so a\n\t * given nav entry resolves to \"the same item\" across menu translations).\n\t *\n\t * If the source menu is missing this throws — callers should validate\n\t * existence via `findById` first to return a clean NOT_FOUND.\n\t */\n\tasync create(input: CreateMenuInput): Promise<Menu> {\n\t\tconst id = ulid();\n\n\t\tlet translationGroup: string = id;\n\t\tlet sourceMenuId: string | null = null;\n\t\tif (input.translationOf) {\n\t\t\tconst source = await this.findById(input.translationOf);\n\t\t\tif (!source) throw new Error(\"Source menu for translation not found\");\n\t\t\ttranslationGroup = source.translationGroup ?? source.id;\n\t\t\tsourceMenuId = source.id;\n\t\t}\n\n\t\tawait withTransaction(this.db, async (trx) => {\n\t\t\tawait trx\n\t\t\t\t.insertInto(\"_emdash_menus\")\n\t\t\t\t.values({\n\t\t\t\t\tid,\n\t\t\t\t\tname: input.name,\n\t\t\t\t\tlabel: input.label,\n\t\t\t\t\t...(input.locale !== undefined ? { locale: input.locale } : {}),\n\t\t\t\t\ttranslation_group: translationGroup,\n\t\t\t\t})\n\t\t\t\t.execute();\n\n\t\t\tif (sourceMenuId) {\n\t\t\t\tconst sourceItems = await trx\n\t\t\t\t\t.selectFrom(\"_emdash_menu_items\")\n\t\t\t\t\t.selectAll()\n\t\t\t\t\t.where(\"menu_id\", \"=\", sourceMenuId)\n\t\t\t\t\t.orderBy(\"sort_order\", \"asc\")\n\t\t\t\t\t.execute();\n\t\t\t\tif (sourceItems.length > 0) {\n\t\t\t\t\t// old-id → new-id map so parent pointers land on the clones.\n\t\t\t\t\tconst idMap = new Map<string, string>();\n\t\t\t\t\tfor (const item of sourceItems) idMap.set(item.id, ulid());\n\n\t\t\t\t\tawait trx\n\t\t\t\t\t\t.insertInto(\"_emdash_menu_items\")\n\t\t\t\t\t\t.values(\n\t\t\t\t\t\t\tsourceItems.map((item) => ({\n\t\t\t\t\t\t\t\tid: idMap.get(item.id)!,\n\t\t\t\t\t\t\t\tmenu_id: id,\n\t\t\t\t\t\t\t\tparent_id: item.parent_id ? (idMap.get(item.parent_id) ?? null) : null,\n\t\t\t\t\t\t\t\tsort_order: item.sort_order,\n\t\t\t\t\t\t\t\ttype: item.type,\n\t\t\t\t\t\t\t\treference_collection: item.reference_collection,\n\t\t\t\t\t\t\t\treference_id: item.reference_id,\n\t\t\t\t\t\t\t\tcustom_url: item.custom_url,\n\t\t\t\t\t\t\t\tlabel: item.label,\n\t\t\t\t\t\t\t\ttitle_attr: item.title_attr,\n\t\t\t\t\t\t\t\ttarget: item.target,\n\t\t\t\t\t\t\t\tcss_classes: item.css_classes,\n\t\t\t\t\t\t\t\t...(input.locale !== undefined ? { locale: input.locale } : {}),\n\t\t\t\t\t\t\t\ttranslation_group: item.translation_group ?? item.id,\n\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.execute();\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\tinvalidateMenuObjectCache();\n\n\t\tconst created = await this.findById(id);\n\t\tif (!created) throw new Error(\"Failed to create menu\");\n\t\treturn created;\n\t}\n\n\tasync update(id: string, input: UpdateMenuInput): Promise<Menu | null> {\n\t\tconst existing = await this.findById(id);\n\t\tif (!existing) return null;\n\n\t\tconst values: Record<string, unknown> = {};\n\t\tif (input.label !== undefined) values.label = input.label;\n\n\t\tif (Object.keys(values).length > 0) {\n\t\t\tawait this.db.updateTable(\"_emdash_menus\").set(values).where(\"id\", \"=\", id).execute();\n\t\t\tinvalidateMenuObjectCache();\n\t\t}\n\n\t\treturn (await this.findById(id))!;\n\t}\n\n\t/**\n\t * Delete a menu. Items are deleted explicitly to avoid relying on the\n\t * `ON DELETE CASCADE` FK declared in migration 005, which migration 036\n\t * removed: that FK is what made #1021 destructive on D1 (the cascade\n\t * fired when the i18n migration dropped `_emdash_menus`), so dropping\n\t * the FK was the fix. The explicit delete keeps the runtime working\n\t * the same way before and after the migration.\n\t */\n\tasync delete(id: string): Promise<boolean> {\n\t\tconst existing = await this.findById(id);\n\t\tif (!existing) return false;\n\n\t\tawait withTransaction(this.db, async (trx) => {\n\t\t\tawait trx.deleteFrom(\"_emdash_menu_items\").where(\"menu_id\", \"=\", id).execute();\n\t\t\tawait trx.deleteFrom(\"_emdash_menus\").where(\"id\", \"=\", id).execute();\n\t\t});\n\t\tinvalidateMenuObjectCache();\n\t\treturn true;\n\t}\n\n\t/**\n\t * List every translation of a menu (by id or translation_group).\n\t *\n\t * Returns `null` when neither the id nor the group resolves to a menu,\n\t * mapped to NOT_FOUND by the handler.\n\t */\n\tasync listTranslations(\n\t\tidOrGroup: string,\n\t): Promise<{ translationGroup: string | null; translations: MenuTranslation[] } | null> {\n\t\tconst anchor = await this.db\n\t\t\t.selectFrom(\"_emdash_menus\")\n\t\t\t.selectAll()\n\t\t\t.where((eb) => eb.or([eb(\"id\", \"=\", idOrGroup), eb(\"translation_group\", \"=\", idOrGroup)]))\n\t\t\t.executeTakeFirst();\n\t\tif (!anchor) return null;\n\n\t\tconst group = anchor.translation_group ?? anchor.id;\n\t\tconst rows = await this.db\n\t\t\t.selectFrom(\"_emdash_menus\")\n\t\t\t.selectAll()\n\t\t\t.where(\"translation_group\", \"=\", group)\n\t\t\t.orderBy(\"locale\", \"asc\")\n\t\t\t.execute();\n\n\t\treturn {\n\t\t\ttranslationGroup: group,\n\t\t\ttranslations: rows.map((row) => ({\n\t\t\t\tid: row.id,\n\t\t\t\tname: row.name,\n\t\t\t\tlocale: row.locale,\n\t\t\t\tlabel: row.label,\n\t\t\t\tupdatedAt: row.updated_at,\n\t\t\t})),\n\t\t};\n\t}\n\n\t// --- Items -------------------------------------------------------------\n\n\t/**\n\t * Insert a menu item. `locale` is propagated from the parent menu so\n\t * `_emdash_menu_items.locale` mirrors the menu's locale (queries can scope\n\t * by locale without a join).\n\t *\n\t * When `sortOrder` is omitted, the next position within the same parent\n\t * scope is used (max + 1). The fresh `translation_group` defaults to the\n\t * item's own id, matching the migration 036 backfill.\n\t */\n\tasync createItem(menuId: string, locale: string, input: CreateMenuItemInput): Promise<MenuItem> {\n\t\tlet sortOrder = input.sortOrder ?? 0;\n\t\tif (input.sortOrder === undefined) {\n\t\t\tconst maxOrder = await this.db\n\t\t\t\t.selectFrom(\"_emdash_menu_items\")\n\t\t\t\t.select(({ fn }) => fn.max(\"sort_order\").as(\"max\"))\n\t\t\t\t.where(\"menu_id\", \"=\", menuId)\n\t\t\t\t.where(\"parent_id\", \"is\", input.parentId ?? null)\n\t\t\t\t.executeTakeFirst();\n\t\t\t// eslint-disable-next-line typescript/no-unsafe-type-assertion -- Kysely fn.max returns unknown; always a number for sort_order column\n\t\t\tsortOrder = ((maxOrder?.max as number) ?? -1) + 1;\n\t\t}\n\n\t\tconst id = ulid();\n\t\tawait this.db\n\t\t\t.insertInto(\"_emdash_menu_items\")\n\t\t\t.values({\n\t\t\t\tid,\n\t\t\t\tmenu_id: menuId,\n\t\t\t\tparent_id: input.parentId ?? null,\n\t\t\t\tsort_order: sortOrder,\n\t\t\t\ttype: input.type,\n\t\t\t\treference_collection: input.referenceCollection ?? null,\n\t\t\t\treference_id: input.referenceId ?? null,\n\t\t\t\tcustom_url: input.customUrl ?? null,\n\t\t\t\tlabel: input.label,\n\t\t\t\ttitle_attr: input.titleAttr ?? null,\n\t\t\t\ttarget: input.target ?? null,\n\t\t\t\tcss_classes: input.cssClasses ?? null,\n\t\t\t\tlocale,\n\t\t\t\ttranslation_group: id,\n\t\t\t})\n\t\t\t.execute();\n\n\t\tinvalidateMenuObjectCache();\n\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"_emdash_menu_items\")\n\t\t\t.selectAll()\n\t\t\t.where(\"id\", \"=\", id)\n\t\t\t.executeTakeFirstOrThrow();\n\t\treturn rowToMenuItem(row);\n\t}\n\n\t/**\n\t * Update a menu item. Caller must ensure the item belongs to the menu —\n\t * the `where(\"menu_id\", \"=\", menuId)` guard prevents cross-menu writes.\n\t * Returns `null` if the item is not found within the menu.\n\t */\n\tasync updateItem(\n\t\tmenuId: string,\n\t\titemId: string,\n\t\tinput: UpdateMenuItemInput,\n\t): Promise<MenuItem | null> {\n\t\tconst existing = await this.db\n\t\t\t.selectFrom(\"_emdash_menu_items\")\n\t\t\t.select(\"id\")\n\t\t\t.where(\"id\", \"=\", itemId)\n\t\t\t.where(\"menu_id\", \"=\", menuId)\n\t\t\t.executeTakeFirst();\n\t\tif (!existing) return null;\n\n\t\tconst values: Record<string, unknown> = {};\n\t\tif (input.label !== undefined) values.label = input.label;\n\t\tif (input.customUrl !== undefined) values.custom_url = input.customUrl;\n\t\tif (input.target !== undefined) values.target = input.target;\n\t\tif (input.titleAttr !== undefined) values.title_attr = input.titleAttr;\n\t\tif (input.cssClasses !== undefined) values.css_classes = input.cssClasses;\n\t\tif (input.parentId !== undefined) values.parent_id = input.parentId;\n\t\tif (input.sortOrder !== undefined) values.sort_order = input.sortOrder;\n\n\t\tif (Object.keys(values).length > 0) {\n\t\t\tawait this.db\n\t\t\t\t.updateTable(\"_emdash_menu_items\")\n\t\t\t\t.set(values)\n\t\t\t\t.where(\"id\", \"=\", itemId)\n\t\t\t\t.execute();\n\t\t\tinvalidateMenuObjectCache();\n\t\t}\n\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"_emdash_menu_items\")\n\t\t\t.selectAll()\n\t\t\t.where(\"id\", \"=\", itemId)\n\t\t\t.executeTakeFirstOrThrow();\n\t\treturn rowToMenuItem(row);\n\t}\n\n\t/** Delete an item scoped to its menu. Returns false if nothing was deleted. */\n\tasync deleteItem(menuId: string, itemId: string): Promise<boolean> {\n\t\tconst result = await this.db\n\t\t\t.deleteFrom(\"_emdash_menu_items\")\n\t\t\t.where(\"id\", \"=\", itemId)\n\t\t\t.where(\"menu_id\", \"=\", menuId)\n\t\t\t.execute();\n\t\tconst deleted = result[0]?.numDeletedRows !== 0n;\n\t\tif (deleted) invalidateMenuObjectCache();\n\t\treturn deleted;\n\t}\n\n\t/**\n\t * Atomic replace: delete every existing item and re-insert in order.\n\t * `parentIndex` (validated by the caller) is resolved against the live\n\t * insert order so children always reference real parent ids.\n\t *\n\t * Returns the count of inserted items (matches the existing handler API).\n\t */\n\tasync setItems(\n\t\tmenuId: string,\n\t\tlocale: string,\n\t\titems: SetMenuItem[],\n\t): Promise<{ itemCount: number }> {\n\t\tawait withTransaction(this.db, async (trx) => {\n\t\t\t// Re-check menu existence INSIDE the transaction. The handler\n\t\t\t// resolved by (name, locale) before this call; if a concurrent\n\t\t\t// menu_delete landed in between, inserting new items would\n\t\t\t// silently orphan them. The FK from migration 005 was removed\n\t\t\t// by migration 036 (#1021) and not restored, so nothing at the\n\t\t\t// schema level stops the orphans. Throw a MenuGoneError so the\n\t\t\t// rollback fires and the handler returns NOT_FOUND with the\n\t\t\t// original menu name in the message.\n\t\t\tconst stillThere = await trx\n\t\t\t\t.selectFrom(\"_emdash_menus\")\n\t\t\t\t.select(\"id\")\n\t\t\t\t.where(\"id\", \"=\", menuId)\n\t\t\t\t.executeTakeFirst();\n\t\t\tif (!stillThere) throw new MenuGoneError(menuId);\n\n\t\t\tawait trx.deleteFrom(\"_emdash_menu_items\").where(\"menu_id\", \"=\", menuId).execute();\n\n\t\t\tconst insertedIds: string[] = [];\n\t\t\tfor (let i = 0; i < items.length; i++) {\n\t\t\t\tconst item = items[i];\n\t\t\t\tif (!item) continue;\n\t\t\t\tconst id = ulid();\n\t\t\t\tconst parentId =\n\t\t\t\t\titem.parentIndex !== undefined ? (insertedIds[item.parentIndex] ?? null) : null;\n\t\t\t\tawait trx\n\t\t\t\t\t.insertInto(\"_emdash_menu_items\")\n\t\t\t\t\t.values({\n\t\t\t\t\t\tid,\n\t\t\t\t\t\tmenu_id: menuId,\n\t\t\t\t\t\tparent_id: parentId,\n\t\t\t\t\t\tsort_order: i,\n\t\t\t\t\t\ttype: item.type,\n\t\t\t\t\t\treference_collection: item.referenceCollection ?? null,\n\t\t\t\t\t\treference_id: item.referenceId ?? null,\n\t\t\t\t\t\tcustom_url: item.customUrl ?? null,\n\t\t\t\t\t\tlabel: item.label,\n\t\t\t\t\t\ttitle_attr: item.titleAttr ?? null,\n\t\t\t\t\t\ttarget: item.target ?? null,\n\t\t\t\t\t\tcss_classes: item.cssClasses ?? null,\n\t\t\t\t\t\tlocale,\n\t\t\t\t\t})\n\t\t\t\t\t.execute();\n\t\t\t\tinsertedIds.push(id);\n\t\t\t}\n\n\t\t\tawait trx\n\t\t\t\t.updateTable(\"_emdash_menus\")\n\t\t\t\t.set({ updated_at: new Date().toISOString() })\n\t\t\t\t.where(\"id\", \"=\", menuId)\n\t\t\t\t.execute();\n\t\t});\n\n\t\tinvalidateMenuObjectCache();\n\t\treturn { itemCount: items.length };\n\t}\n\n\t/**\n\t * Batch reorder items. Each entry is applied scoped to the menu so a\n\t * malicious payload cannot move foreign items into this menu's siblings.\n\t */\n\tasync reorderItems(menuId: string, items: ReorderItem[]): Promise<MenuItem[]> {\n\t\tinvalidateMenuObjectCache();\n\t\treturn withTransaction(this.db, async (trx) => {\n\t\t\tfor (const item of items) {\n\t\t\t\tawait trx\n\t\t\t\t\t.updateTable(\"_emdash_menu_items\")\n\t\t\t\t\t.set({ parent_id: item.parentId, sort_order: item.sortOrder })\n\t\t\t\t\t.where(\"id\", \"=\", item.id)\n\t\t\t\t\t.where(\"menu_id\", \"=\", menuId)\n\t\t\t\t\t.execute();\n\t\t\t}\n\n\t\t\tconst rows = await trx\n\t\t\t\t.selectFrom(\"_emdash_menu_items\")\n\t\t\t\t.selectAll()\n\t\t\t\t.where(\"menu_id\", \"=\", menuId)\n\t\t\t\t.orderBy(\"sort_order\", \"asc\")\n\t\t\t\t.execute();\n\t\t\treturn rows.map(rowToMenuItem);\n\t\t});\n\t}\n}\n","/**\n * Menu CRUD handlers.\n *\n * Business logic for menu and menu-item endpoints. Routes are thin wrappers\n * that parse input, check auth, and call these.\n *\n * i18n: Menus are per-locale. `(name, locale)` is unique, so the same `name`\n * (e.g. \"primary\") can exist in several locales within one translation_group.\n * Menu items carry a `locale` + `translation_group` as well, and their\n * `reference_id` points at the referenced content's translation_group (not a\n * specific row id), so a single menu item target survives content translations.\n */\n\nimport type { Kysely } from \"kysely\";\n\nimport {\n\tMenuGoneError,\n\tMenuRepository,\n\ttype CreateMenuItemInput as CreateMenuItemRepoInput,\n\ttype Menu,\n\ttype MenuItem,\n\ttype MenuListItem,\n\ttype MenuWithItems,\n\ttype SetMenuItem,\n\ttype UpdateMenuItemInput as UpdateMenuItemRepoInput,\n} from \"../../database/repositories/menu.js\";\nimport type { Database } from \"../../database/types.js\";\nimport { getI18nConfig, resolveConfiguredLocale } from \"../../i18n/config.js\";\nimport type { ApiResult } from \"../types.js\";\n\n// Re-export entity types so route files and tests can import them from the\n// handler module without having to know about the repository layout.\nexport type {\n\tMenu,\n\tMenuItem,\n\tMenuListItem,\n\tMenuTranslation,\n\tMenuWithItems,\n} from \"../../database/repositories/menu.js\";\n\nexport interface MenuTranslationsResponse {\n\ttranslationGroup: string | null;\n\ttranslations: Array<{\n\t\tid: string;\n\t\tname: string;\n\t\tlocale: string;\n\t\tlabel: string;\n\t\tupdatedAt: string;\n\t}>;\n}\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Error returned when a menu lookup by `name` matches multiple locale\n * variants and the caller did not pass `locale` to disambiguate. Maps to\n * HTTP 400 via `mapErrorStatus`. The available locales are surfaced in the\n * message so MCP/REST callers can recover by re-issuing with `locale`.\n */\nfunction ambiguousMenuLocaleError(\n\tname: string,\n\tlocales: readonly string[],\n): { success: false; error: { code: \"AMBIGUOUS_LOCALE\"; message: string } } {\n\tconst sortedLocales = locales.toSorted();\n\treturn {\n\t\tsuccess: false,\n\t\terror: {\n\t\t\tcode: \"AMBIGUOUS_LOCALE\",\n\t\t\tmessage: `Menu '${name}' exists in multiple locales (${sortedLocales.join(\n\t\t\t\t\", \",\n\t\t\t)}); pass 'locale' to disambiguate.`,\n\t\t},\n\t};\n}\n\ntype ResolveMenuResult =\n\t| { success: true; menu: Menu }\n\t| { success: false; error: { code: \"NOT_FOUND\" | \"AMBIGUOUS_LOCALE\"; message: string } };\n\n/**\n * Resolve a menu by name + optional locale to a single Menu, surfacing the\n * canonical NOT_FOUND / AMBIGUOUS_LOCALE errors. Every item handler relies on\n * this to translate (name, locale) into an unambiguous menu row.\n */\nasync function resolveMenu(\n\trepo: MenuRepository,\n\tname: string,\n\toptions: { locale?: string },\n): Promise<ResolveMenuResult> {\n\tconst locale = options.locale ? resolveConfiguredLocale(options.locale) : undefined;\n\tconst matches = await repo.findByName(name, { locale });\n\tif (matches.length === 0) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: {\n\t\t\t\tcode: \"NOT_FOUND\",\n\t\t\t\tmessage: `Menu '${name}' not found${options.locale ? ` in locale '${options.locale}'` : \"\"}`,\n\t\t\t},\n\t\t};\n\t}\n\tif (matches.length > 1) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: ambiguousMenuLocaleError(\n\t\t\t\tname,\n\t\t\t\tmatches.map((m) => m.locale),\n\t\t\t).error,\n\t\t};\n\t}\n\treturn { success: true, menu: matches[0] };\n}\n\n// ---------------------------------------------------------------------------\n// Menu handlers\n// ---------------------------------------------------------------------------\n\n/**\n * List menus with item counts. Filter by `locale` when provided.\n */\nexport async function handleMenuList(\n\tdb: Kysely<Database>,\n\toptions: { locale?: string } = {},\n): Promise<ApiResult<MenuListItem[]>> {\n\ttry {\n\t\tconst repo = new MenuRepository(db);\n\t\tconst locale = options.locale ? resolveConfiguredLocale(options.locale) : undefined;\n\t\tconst items = await repo.findMany({ locale });\n\t\treturn { success: true, data: items };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"MENU_LIST_ERROR\", message: \"Failed to fetch menus\" },\n\t\t};\n\t}\n}\n\n/**\n * Create a new menu. When `translationOf` is supplied the new menu joins the\n * source menu's translation_group (and gets the source's items cloned by the\n * repository).\n */\nexport async function handleMenuCreate(\n\tdb: Kysely<Database>,\n\tinput: { name: string; label: string; locale?: string; translationOf?: string },\n): Promise<ApiResult<Menu>> {\n\ttry {\n\t\t// Translating from a source menu only makes sense when the caller\n\t\t// names the target locale: otherwise we'd silently clone into the\n\t\t// configured default, which is almost never what's intended (and\n\t\t// will collide if the source is already the default-locale menu).\n\t\t// Enforced here so REST/SDK callers get the same guard as MCP.\n\t\tif (input.translationOf && !input.locale) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: {\n\t\t\t\t\tcode: \"VALIDATION_ERROR\",\n\t\t\t\t\tmessage: \"`locale` is required when `translationOf` is provided\",\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\tconst repo = new MenuRepository(db);\n\n\t\t// Existence check up front so the repo's \"Source not found\" throw\n\t\t// becomes a clean NOT_FOUND on the API.\n\t\tif (input.translationOf) {\n\t\t\tconst source = await repo.findById(input.translationOf);\n\t\t\tif (!source) {\n\t\t\t\treturn {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: { code: \"NOT_FOUND\", message: \"Source menu for translation not found\" },\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\n\t\t// Duplicate guard: same (name, locale). Falls back to the configured\n\t\t// defaultLocale to match the column DEFAULT set by migration 036.\n\t\tconst effectiveLocale = input.locale\n\t\t\t? resolveConfiguredLocale(input.locale)\n\t\t\t: (getI18nConfig()?.defaultLocale ?? \"en\");\n\t\tif (await repo.existsByNameAndLocale(input.name, effectiveLocale)) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: {\n\t\t\t\t\tcode: \"CONFLICT\",\n\t\t\t\t\tmessage: `Menu \"${input.name}\" already exists${\n\t\t\t\t\t\tinput.locale ? ` in locale \"${input.locale}\"` : \"\"\n\t\t\t\t\t}`,\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\tconst menu = await repo.create({ ...input, locale: effectiveLocale });\n\t\treturn { success: true, data: menu };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"MENU_CREATE_ERROR\", message: \"Failed to create menu\" },\n\t\t};\n\t}\n}\n\n/**\n * Get a single menu by name. Honours an optional `locale` filter; when two\n * menus share a name across locales, the locale distinguishes them.\n *\n * Historical behaviour: when `locale` is omitted, returns the lowest-locale\n * match (deterministic). Mirrors the pre-repo handler.\n */\nexport async function handleMenuGet(\n\tdb: Kysely<Database>,\n\tname: string,\n\toptions: { locale?: string } = {},\n): Promise<ApiResult<MenuWithItems>> {\n\ttry {\n\t\tconst repo = new MenuRepository(db);\n\t\tconst locale = options.locale ? resolveConfiguredLocale(options.locale) : undefined;\n\t\tconst matches = await repo.findByName(name, { locale });\n\t\tif (matches.length === 0) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"NOT_FOUND\", message: `Menu '${name}' not found` },\n\t\t\t};\n\t\t}\n\t\tconst menu = matches[0];\n\t\tconst items = await repo.findItems(menu.id);\n\t\treturn { success: true, data: { ...menu, items } };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"MENU_GET_ERROR\", message: \"Failed to fetch menu\" },\n\t\t};\n\t}\n}\n\n/**\n * Get a menu by id. Useful when the caller already has the id (e.g. after\n * creating a translation and navigating to it).\n */\nexport async function handleMenuGetById(\n\tdb: Kysely<Database>,\n\tid: string,\n): Promise<ApiResult<MenuWithItems>> {\n\ttry {\n\t\tconst repo = new MenuRepository(db);\n\t\tconst menu = await repo.findWithItems(id);\n\t\tif (!menu) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"NOT_FOUND\", message: `Menu '${id}' not found` },\n\t\t\t};\n\t\t}\n\t\treturn { success: true, data: menu };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"MENU_GET_ERROR\", message: \"Failed to fetch menu\" },\n\t\t};\n\t}\n}\n\n/**\n * Update a menu's label. The name + locale are immutable.\n */\nexport async function handleMenuUpdate(\n\tdb: Kysely<Database>,\n\tname: string,\n\tinput: { label?: string; locale?: string },\n): Promise<ApiResult<Menu>> {\n\ttry {\n\t\tconst repo = new MenuRepository(db);\n\t\tconst resolved = await resolveMenu(repo, name, { locale: input.locale });\n\t\tif (!resolved.success) return resolved;\n\t\tconst updated = await repo.update(resolved.menu.id, { label: input.label });\n\t\tif (!updated) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"NOT_FOUND\", message: `Menu '${name}' not found` },\n\t\t\t};\n\t\t}\n\t\treturn { success: true, data: updated };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"MENU_UPDATE_ERROR\", message: \"Failed to update menu\" },\n\t\t};\n\t}\n}\n\n/**\n * Delete a menu (and its items, via the repository's explicit cleanup).\n */\nexport async function handleMenuDelete(\n\tdb: Kysely<Database>,\n\tname: string,\n\toptions: { locale?: string } = {},\n): Promise<ApiResult<{ deleted: true }>> {\n\ttry {\n\t\tconst repo = new MenuRepository(db);\n\t\tconst resolved = await resolveMenu(repo, name, options);\n\t\tif (!resolved.success) return resolved;\n\t\tawait repo.delete(resolved.menu.id);\n\t\treturn { success: true, data: { deleted: true } };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"MENU_DELETE_ERROR\", message: \"Failed to delete menu\" },\n\t\t};\n\t}\n}\n\n/**\n * List every translation of a menu (by id or translation_group).\n */\nexport async function handleMenuTranslations(\n\tdb: Kysely<Database>,\n\tidOrGroup: string,\n): Promise<ApiResult<MenuTranslationsResponse>> {\n\ttry {\n\t\tconst repo = new MenuRepository(db);\n\t\tconst result = await repo.listTranslations(idOrGroup);\n\t\tif (!result) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"NOT_FOUND\", message: \"Menu not found\" },\n\t\t\t};\n\t\t}\n\t\treturn { success: true, data: result };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"MENU_TRANSLATIONS_ERROR\", message: \"Failed to list menu translations\" },\n\t\t};\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Menu item handlers\n// ---------------------------------------------------------------------------\n\nexport type CreateMenuItemInput = CreateMenuItemRepoInput;\nexport type UpdateMenuItemInput = UpdateMenuItemRepoInput;\nexport type MenuSetItemsInput = SetMenuItem;\n\n/**\n * Add an item to a menu. The item inherits the menu's locale.\n */\nexport async function handleMenuItemCreate(\n\tdb: Kysely<Database>,\n\tmenuName: string,\n\tinput: CreateMenuItemInput,\n\toptions: { locale?: string } = {},\n): Promise<ApiResult<MenuItem>> {\n\ttry {\n\t\tconst repo = new MenuRepository(db);\n\t\tconst resolved = await resolveMenu(repo, menuName, options);\n\t\tif (!resolved.success) return resolved;\n\n\t\tconst item = await repo.createItem(resolved.menu.id, resolved.menu.locale, input);\n\t\treturn { success: true, data: item };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"MENU_ITEM_CREATE_ERROR\", message: \"Failed to create menu item\" },\n\t\t};\n\t}\n}\n\n/**\n * Update a menu item.\n */\nexport async function handleMenuItemUpdate(\n\tdb: Kysely<Database>,\n\tmenuName: string,\n\titemId: string,\n\tinput: UpdateMenuItemInput,\n\toptions: { locale?: string } = {},\n): Promise<ApiResult<MenuItem>> {\n\ttry {\n\t\tconst repo = new MenuRepository(db);\n\t\tconst resolved = await resolveMenu(repo, menuName, options);\n\t\tif (!resolved.success) return resolved;\n\n\t\tconst updated = await repo.updateItem(resolved.menu.id, itemId, input);\n\t\tif (!updated) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"NOT_FOUND\", message: \"Menu item not found\" },\n\t\t\t};\n\t\t}\n\t\treturn { success: true, data: updated };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"MENU_ITEM_UPDATE_ERROR\", message: \"Failed to update menu item\" },\n\t\t};\n\t}\n}\n\n/**\n * Delete a menu item.\n */\nexport async function handleMenuItemDelete(\n\tdb: Kysely<Database>,\n\tmenuName: string,\n\titemId: string,\n\toptions: { locale?: string } = {},\n): Promise<ApiResult<{ deleted: true }>> {\n\ttry {\n\t\tconst repo = new MenuRepository(db);\n\t\tconst resolved = await resolveMenu(repo, menuName, options);\n\t\tif (!resolved.success) return resolved;\n\n\t\tconst deleted = await repo.deleteItem(resolved.menu.id, itemId);\n\t\tif (!deleted) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"NOT_FOUND\", message: \"Menu item not found\" },\n\t\t\t};\n\t\t}\n\t\treturn { success: true, data: { deleted: true } };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"MENU_ITEM_DELETE_ERROR\", message: \"Failed to delete menu item\" },\n\t\t};\n\t}\n}\n\nexport interface ReorderItem {\n\tid: string;\n\tparentId: string | null;\n\tsortOrder: number;\n}\n\n// ---------------------------------------------------------------------------\n// Atomic-replace menu items (used by the MCP `menu_set_items` tool and admin)\n// ---------------------------------------------------------------------------\n\n/**\n * Replace the entire set of items for a menu in one atomic transaction.\n *\n * Existing items are deleted and the new list is inserted in the order\n * provided. `parentIndex` references resolve to actual parent IDs as the\n * insert proceeds.\n */\nexport async function handleMenuSetItems(\n\tdb: Kysely<Database>,\n\tmenuName: string,\n\titems: MenuSetItemsInput[],\n\toptions: { locale?: string } = {},\n): Promise<ApiResult<{ name: string; itemCount: number }>> {\n\t// Validate parentIndex references — must be strictly earlier so the array\n\t// can be inserted in order with parents resolved first. Negative indices\n\t// are caught by Zod's `.nonnegative()` at the MCP boundary, but we guard\n\t// explicitly so REST routes / direct handler use get the same error.\n\tfor (let i = 0; i < items.length; i++) {\n\t\tconst item = items[i];\n\t\tif (item?.parentIndex !== undefined) {\n\t\t\tif (item.parentIndex < 0 || item.parentIndex >= i) {\n\t\t\t\treturn {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: {\n\t\t\t\t\t\tcode: \"VALIDATION_ERROR\",\n\t\t\t\t\t\tmessage: `item[${i}].parentIndex (${item.parentIndex}) must reference an earlier item`,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t}\n\n\ttry {\n\t\tconst repo = new MenuRepository(db);\n\t\tconst resolved = await resolveMenu(repo, menuName, options);\n\t\tif (!resolved.success) return resolved;\n\n\t\tconst { itemCount } = await repo.setItems(resolved.menu.id, resolved.menu.locale, items);\n\t\treturn { success: true, data: { name: menuName, itemCount } };\n\t} catch (error) {\n\t\t// `MenuGoneError` is thrown from inside the repository transaction\n\t\t// when the menu was deleted concurrently between `resolveMenu` and the\n\t\t// setItems write. Returning NOT_FOUND mirrors the original handler's\n\t\t// in-transaction `notFoundSentinel` branch and keeps the response\n\t\t// shape stable for REST/MCP callers.\n\t\tif (error instanceof MenuGoneError) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: {\n\t\t\t\t\tcode: \"NOT_FOUND\",\n\t\t\t\t\tmessage: `Menu '${menuName}' not found${\n\t\t\t\t\t\toptions.locale ? ` in locale '${options.locale}'` : \"\"\n\t\t\t\t\t}`,\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t\tconsole.error(\"[emdash] handleMenuSetItems failed:\", error);\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"MENU_SET_ITEMS_ERROR\", message: \"Failed to set menu items\" },\n\t\t};\n\t}\n}\n\n/**\n * Batch reorder menu items.\n */\nexport async function handleMenuItemReorder(\n\tdb: Kysely<Database>,\n\tmenuName: string,\n\titems: ReorderItem[],\n\toptions: { locale?: string } = {},\n): Promise<ApiResult<MenuItem[]>> {\n\ttry {\n\t\tconst repo = new MenuRepository(db);\n\t\tconst resolved = await resolveMenu(repo, menuName, options);\n\t\tif (!resolved.success) return resolved;\n\n\t\tconst updated = await repo.reorderItems(resolved.menu.id, items);\n\t\treturn { success: true, data: updated };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"MENU_REORDER_ERROR\", message: \"Failed to reorder menu items\" },\n\t\t};\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;AA6BA,IAAa,gBAAb,cAAmC,MAAM;CACxC,YAAY,AAAgB,QAAgB;AAC3C,QAAM,QAAQ,OAAO,mCAAmC;EAD7B;AAE3B,OAAK,OAAO;;;AA4Hd,SAAS,UAAU,KAAkC;AACpD,QAAO;EACN,IAAI,IAAI;EACR,MAAM,IAAI;EACV,OAAO,IAAI;EACX,WAAW,IAAI;EACf,WAAW,IAAI;EACf,QAAQ,IAAI;EACZ,kBAAkB,IAAI;EACtB;;AAGF,SAAS,cAAc,KAA0C;AAChE,QAAO;EACN,IAAI,IAAI;EACR,QAAQ,IAAI;EACZ,UAAU,IAAI;EACd,WAAW,IAAI;EACf,MAAM,IAAI;EACV,qBAAqB,IAAI;EACzB,aAAa,IAAI;EACjB,WAAW,IAAI;EACf,OAAO,IAAI;EACX,WAAW,IAAI;EACf,QAAQ,IAAI;EACZ,YAAY,IAAI;EAChB,WAAW,IAAI;EACf,QAAQ,IAAI;EACZ,kBAAkB,IAAI;EACtB;;AAOF,IAAa,iBAAb,MAA4B;CAC3B,YAAY,AAAQ,IAAsB;EAAtB;;;;;;;CASpB,MAAM,SAAS,UAA+B,EAAE,EAA2B;EAE1E,IAAI,QAAQ,KAAK,GACf,WAAW,qBAAqB,CAChC,SAAS,2BAA2B,aAAa,OAAO,CACxD,QAAQ,EAA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