@murumets-ee/media 0.19.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/dist/admin.d.mts +19 -16
  2. package/dist/admin.d.mts.map +1 -1
  3. package/dist/admin.mjs +1 -1
  4. package/dist/{client-CHGSsUxS.mjs → client-BcA8CDBk.mjs} +2 -2
  5. package/dist/{client-CHGSsUxS.mjs.map → client-BcA8CDBk.mjs.map} +1 -1
  6. package/dist/client.d.mts +1 -1
  7. package/dist/image-styles-settings.d.mts +4 -5
  8. package/dist/image-styles-settings.d.mts.map +1 -1
  9. package/dist/image-styles.d.mts +2 -3
  10. package/dist/image-styles.d.mts.map +1 -1
  11. package/dist/index.d.mts +1 -1
  12. package/dist/picker.d.mts +6 -7
  13. package/dist/picker.d.mts.map +1 -1
  14. package/dist/plugin-BPabn1pf.mjs +2 -0
  15. package/dist/plugin-BPabn1pf.mjs.map +1 -0
  16. package/dist/plugin.d.mts +9 -3
  17. package/dist/plugin.d.mts.map +1 -1
  18. package/dist/plugin.mjs +1 -1
  19. package/dist/plugin.mjs.map +1 -1
  20. package/dist/processing.d.mts +1 -1
  21. package/dist/query-client.d.mts +1 -1
  22. package/dist/regenerate-variants-DJIFSrdC.mjs +2 -0
  23. package/dist/regenerate-variants-DJIFSrdC.mjs.map +1 -0
  24. package/dist/regenerate-variants-DtA5pKjj.mjs +2 -0
  25. package/dist/regenerate-variants-DtA5pKjj.mjs.map +1 -0
  26. package/dist/{resolve-image-styles-2sa0O7wU.mjs → resolve-image-styles-Dqaa5QsX.mjs} +2 -2
  27. package/dist/{resolve-image-styles-2sa0O7wU.mjs.map → resolve-image-styles-Dqaa5QsX.mjs.map} +1 -1
  28. package/dist/routes-tHvb9cgv.mjs +2 -0
  29. package/dist/routes-tHvb9cgv.mjs.map +1 -0
  30. package/dist/{types-BMW3aeEB.d.mts → types-CqjShq2U.d.mts} +15 -16
  31. package/dist/types-CqjShq2U.d.mts.map +1 -0
  32. package/dist/usage-BwUdYWkA.mjs +2 -0
  33. package/dist/usage-BwUdYWkA.mjs.map +1 -0
  34. package/dist/usage.d.mts +3 -3
  35. package/dist/usage.d.mts.map +1 -1
  36. package/dist/usage.mjs +1 -1
  37. package/dist/usage.mjs.map +1 -1
  38. package/package.json +10 -9
  39. package/dist/plugin-DZaF1BHS.mjs +0 -2
  40. package/dist/plugin-DZaF1BHS.mjs.map +0 -1
  41. package/dist/regenerate-variants-CuHnSFS5.mjs +0 -2
  42. package/dist/regenerate-variants-CuHnSFS5.mjs.map +0 -1
  43. package/dist/regenerate-variants-rNGOuUJc.mjs +0 -2
  44. package/dist/regenerate-variants-rNGOuUJc.mjs.map +0 -1
  45. package/dist/routes-BFRoQhZB.mjs +0 -2
  46. package/dist/routes-BFRoQhZB.mjs.map +0 -1
  47. package/dist/types-BMW3aeEB.d.mts.map +0 -1
  48. package/dist/usage-aqV6Z9d_.mjs +0 -2
  49. package/dist/usage-aqV6Z9d_.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"plugin.mjs","names":[],"sources":["../src/admin/routes.ts","../src/plugin.ts"],"sourcesContent":["/**\n * Media admin routes for the centralized admin API handler.\n *\n * Provides media-specific operations: upload, URL resolution, delete with storage cleanup,\n * image style settings, and variant regeneration.\n *\n * Standard entity CRUD (PATCH with translations) falls through to the generic entity\n * handler — add `Media` to the `entities` array in your handler config.\n *\n * @example\n * ```typescript\n * import { createAdminApiHandler } from '@murumets-ee/admin-ui/server'\n * import { mediaRoutes } from '@murumets-ee/media/admin'\n * import { Media } from '@murumets-ee/media'\n *\n * const handler = createAdminApiHandler({\n * authenticate: async (req) => { ... },\n * entities: [Article, Media],\n * routes: [mediaRoutes()],\n * })\n * ```\n */\n\nimport type { AdminRoute, AuditLogFn, AuthUser } from '@murumets-ee/core'\nimport type { MediaClient } from '../client.js'\nimport type { MediaPickerItem, MediaPickerListResult } from '../picker/types.js'\n\n// ---------------------------------------------------------------------------\n// Validation\n// ---------------------------------------------------------------------------\n\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i\n\nfunction isValidUuid(value: string | undefined): value is string {\n return value !== undefined && UUID_RE.test(value)\n}\n\n// ---------------------------------------------------------------------------\n// Per-request MediaClient factory\n// ---------------------------------------------------------------------------\n//\n// MediaClient and its AdminClient MUST be built per-request — AdminClient's\n// context resolver is captured eagerly at construction (see\n// buildContextResolver in @murumets-ee/core/clients). A module-level singleton\n// would bake the first request's user + tenant scope into every subsequent\n// request's writes — a cross-request permission/scope leak.\n//\n// Storage config is process-global and safe to cache once.\n\nlet storagePromise: Promise<Awaited<ReturnType<typeof import('@murumets-ee/storage').createStorageClient>>> | null = null\n\nasync function getStorage() {\n if (!storagePromise) {\n storagePromise = (async () => {\n const { getApp } = await import('@murumets-ee/core')\n const { createStorageClient } = await import('@murumets-ee/storage')\n const { getStorageConfig } = await import('@murumets-ee/storage/plugin')\n const app = getApp()\n return createStorageClient(getStorageConfig(), { app })\n })()\n }\n return storagePromise\n}\n\nasync function getClient(): Promise<MediaClient> {\n const { createAdminClient } = await import('@murumets-ee/core/clients')\n const { MediaClient } = await import('../client.js')\n const { Media } = await import('../entity.js')\n const storage = await getStorage()\n const admin = createAdminClient(Media)\n return new MediaClient({ admin, storage })\n}\n\n// ---------------------------------------------------------------------------\n// Response helpers\n// ---------------------------------------------------------------------------\n\nfunction json(data: unknown, status = 200) {\n return new Response(JSON.stringify(data), {\n status,\n headers: { 'Content-Type': 'application/json' },\n })\n}\n\nfunction errorJson(message: string, status: number) {\n return json({ error: message }, status)\n}\n\n// ---------------------------------------------------------------------------\n// Handlers\n// ---------------------------------------------------------------------------\n\nasync function handleGet(\n req: Request,\n { segments }: { segments: string[]; user: AuthUser; audit?: AuditLogFn },\n): Promise<Response> {\n const { isStorageConfigured, getStorageConfigReason } = await import('@murumets-ee/storage')\n\n // GET /media/:id/usage — DB-only lookup, also safe without storage.\n if (segments.length === 2 && segments[1] === 'usage') {\n const id = segments[0]\n if (!isValidUuid(id)) return errorJson('Invalid media ID format', 400)\n\n const { findMediaUsages } = await import('../usage.js')\n const { getApp } = await import('@murumets-ee/core')\n const app = getApp()\n const usages = await findMediaUsages(id, app.db.readWrite)\n return json({ usages })\n }\n\n // GET /media/:id — validate UUID up front so a bad request still 400s\n // when storage happens to be unconfigured (matches the DELETE handler).\n const singleId = segments.length > 0 ? segments[0] : undefined\n if (singleId !== undefined && !isValidUuid(singleId)) {\n return errorJson('Invalid media ID format', 400)\n }\n\n // Everything below needs a working storage client. If env isn't wired,\n // return a structured \"disabled\" response rather than a 500 — the\n // media list page renders a banner and new admins can finish onboarding\n // without being blocked on a crash loop.\n if (!isStorageConfigured()) {\n const reason = getStorageConfigReason() ?? 'Storage not configured'\n if (segments.length > 0) {\n // Single item / other sub-paths — treat as not-found-ish to avoid\n // leaking existence; include reason so the UI can surface it.\n return json(\n { error: reason, configured: false, reason },\n 503,\n )\n }\n // GET /media — empty list + disabled flag for the picker's banner.\n const response: MediaPickerListResult & { configured: false; reason: string } = {\n items: [],\n total: 0,\n configured: false,\n reason,\n }\n return json(response)\n }\n\n const client = await getClient()\n\n // GET /media/:id — single item with URL (full record for EntityForm + picker)\n if (singleId !== undefined) {\n const record = await client.findById(singleId)\n if (!record) return errorJson('Media not found', 404)\n\n const url = await client.getUrl(singleId)\n return json({ ...record, url })\n }\n\n // GET /media — list with search/filter + batch URL resolution\n const url = new URL(req.url)\n const search = url.searchParams.get('search') ?? undefined\n const mediaType = url.searchParams.get('mediaType') ?? undefined\n const limit = Math.min(Math.max(Number(url.searchParams.get('limit')) || 24, 1), 100)\n const offset = Math.max(Number(url.searchParams.get('offset')) || 0, 0)\n\n const result = await client.findMany({\n ...(search !== undefined && { search }),\n ...(mediaType !== undefined && {\n mediaType: mediaType as 'image' | 'video' | 'audio' | 'document' | 'other',\n }),\n limit,\n offset,\n })\n\n // Resolve original URLs + thumbnail variant URLs for all items\n const ids = result.items.map((item) => item.id)\n const [urlMap, thumbMap] = await Promise.all([\n client.getUrls(ids),\n client.getVariantUrls(ids, 'thumbnail'),\n ])\n\n const items: (MediaPickerItem & { thumbnailUrl?: string })[] = result.items.map((item) => {\n const thumbnailUrl = thumbMap.get(item.id)\n return {\n id: item.id,\n title: item.title ?? null,\n alt: item.alt ?? null,\n filename: item.filename,\n mimeType: item.mimeType,\n size: item.size,\n mediaType: item.mediaType,\n url: urlMap.get(item.id) ?? '',\n ...(thumbnailUrl !== undefined && { thumbnailUrl }),\n width: item.width ?? null,\n height: item.height ?? null,\n }\n })\n\n const response: MediaPickerListResult = { items, total: result.total }\n return json(response)\n}\n\nasync function handlePost(\n req: Request,\n {\n segments,\n user,\n audit,\n checkPermission,\n }: {\n segments: string[]\n user: AuthUser\n audit?: AuditLogFn\n checkPermission: (resource: string, action: string) => boolean\n },\n): Promise<Response> {\n const { isStorageConfigured, getStorageConfigReason } = await import('@murumets-ee/storage')\n\n // POST /media/regenerate-variants — creates new variant files.\n // Framework-level gate already requires 'media.create' (METHOD_TO_ACTION maps POST → create),\n // so we don't need a redundant handler check here. Leaving a brief assert for defence-in-depth.\n if (segments.length === 1 && segments[0] === 'regenerate-variants') {\n if (!checkPermission('media', 'create')) {\n return errorJson('Forbidden: media create permission required for variant regeneration', 403)\n }\n if (!isStorageConfigured()) {\n return errorJson(\n getStorageConfigReason() ?? 'Storage not configured',\n 503,\n )\n }\n\n const { regenerateAllVariants } = await import('../regenerate-variants.js')\n const { getApp, getContext } = await import('@murumets-ee/core')\n const { resolveImageStyles } = await import('../resolve-image-styles.js')\n const { createStorageClient } = await import('@murumets-ee/storage')\n const { getStorageConfig } = await import('@murumets-ee/storage/plugin')\n\n const app = getApp()\n const styles = await resolveImageStyles(app, app.logger)\n if (!styles || Object.keys(styles).length === 0) {\n return errorJson('No image styles configured', 400)\n }\n\n const storageConfig = getStorageConfig()\n const storage = createStorageClient(storageConfig, { app })\n\n const result = await regenerateAllVariants({\n db: app.db.readWrite,\n storage,\n logger: app.logger.child({ media: true }),\n styles,\n contextResolver: () => {\n const ctx = getContext()\n if (!ctx?.user || !ctx?.checker) return undefined\n return {\n user: ctx.user,\n checker: ctx.checker,\n ...(ctx.scope !== undefined && { scope: ctx.scope }),\n }\n },\n })\n\n audit?.({\n action: 'media.regenerate_variants',\n userId: user.id,\n ...(user.name !== undefined && { userName: user.name }),\n metadata: { total: result.total, processed: result.processed, errors: result.errors },\n })\n\n return json(result)\n }\n\n // POST /media — upload file (requires media create permission)\n if (!checkPermission('media', 'create')) {\n return errorJson('Forbidden: media create permission required for upload', 403)\n }\n if (!isStorageConfigured()) {\n return errorJson(\n getStorageConfigReason() ?? 'Storage not configured',\n 503,\n )\n }\n\n const client = await getClient()\n\n const formData = await req.formData()\n const file = formData.get('file') as File | null\n if (!file || file.size === 0) {\n return errorJson('No file provided', 400)\n }\n\n // Guard against oversized uploads (50 MB limit)\n const MAX_UPLOAD_SIZE = 50 * 1024 * 1024\n if (file.size > MAX_UPLOAD_SIZE) {\n return errorJson(\n `File too large: ${(file.size / 1024 / 1024).toFixed(1)} MB exceeds 50 MB limit`,\n 400,\n )\n }\n\n const buffer = Buffer.from(await file.arrayBuffer())\n\n // Detect actual MIME type from file content (prevents spoofing)\n const { detectMimeType } = await import('@murumets-ee/storage')\n const { mimeType, mismatch } = await detectMimeType(\n buffer,\n file.type || 'application/octet-stream',\n )\n if (mismatch) {\n return errorJson(\n `File content doesn't match declared type: claimed ${file.type}, detected ${mimeType}`,\n 400,\n )\n }\n\n const result = await client.upload(buffer, {\n filename: file.name,\n mimeType,\n size: file.size,\n uploadedBy: user.id,\n })\n\n const item: MediaPickerItem = {\n id: result.media.id,\n title: result.media.title ?? null,\n alt: result.media.alt ?? null,\n filename: result.media.filename,\n mimeType: result.media.mimeType,\n size: result.media.size,\n mediaType: result.media.mediaType,\n url: result.url,\n width: result.media.width ?? null,\n height: result.media.height ?? null,\n }\n\n audit?.({\n action: 'media.upload',\n entityType: 'media',\n entityId: result.media.id,\n userId: user.id,\n ...(user.name !== undefined && { userName: user.name }),\n changes: {\n filename: result.media.filename,\n mimeType: result.media.mimeType,\n size: result.media.size,\n mediaType: result.media.mediaType,\n },\n })\n\n return json(item, 201)\n}\n\nasync function handleDelete(\n _req: Request,\n {\n segments,\n user,\n audit,\n checkPermission,\n }: {\n segments: string[]\n user: AuthUser\n audit?: AuditLogFn\n checkPermission: (resource: string, action: string) => boolean\n },\n): Promise<Response> {\n if (!checkPermission('media', 'delete')) {\n return errorJson('Forbidden: media delete permission required', 403)\n }\n\n if (segments.length === 0) {\n return errorJson('Media ID required', 400)\n }\n\n const id = segments[0]\n if (!isValidUuid(id)) return errorJson('Invalid media ID format', 400)\n\n const { isStorageConfigured, getStorageConfigReason } = await import('@murumets-ee/storage')\n if (!isStorageConfigured()) {\n // Can't safely delete — MediaClient needs storage to remove the\n // actual object, and partial delete (DB row gone, object orphaned)\n // would leak storage. Surface the reason so the UI can display it.\n return errorJson(getStorageConfigReason() ?? 'Storage not configured', 503)\n }\n\n // AdminClient.delete() checks entity_refs and throws ReferencedEntityError\n // if this media is still referenced. The error bubbles to the caller's\n // error handler which returns 409 with usage details.\n const client = await getClient()\n await client.delete(id)\n\n audit?.({\n action: 'media.delete',\n entityType: 'media',\n entityId: id,\n userId: user.id,\n ...(user.name !== undefined && { userName: user.name }),\n })\n\n return json({ deleted: 1 })\n}\n\n// ---------------------------------------------------------------------------\n// Route factory\n// ---------------------------------------------------------------------------\n\n/**\n * Create admin API routes for media-specific operations.\n *\n * Standard entity CRUD (PATCH with translations) is handled by the generic entity\n * handler — add `Media` to the `entities` array in your handler config.\n *\n * Routes handled by this plugin:\n * - `GET /api/admin/media` — List media with search/filter + URLs\n * - `GET /api/admin/media/:id` — Get single media item with URL\n * - `GET /api/admin/media/:id/usage` — Find entities referencing this media\n * - `POST /api/admin/media` — Upload file (FormData with `file` field)\n * - `POST /api/admin/media/regenerate-variants` — Regenerate all image variants (admin only)\n * - `DELETE /api/admin/media/:id` — Delete media + storage file (blocked if in use)\n *\n * Image style settings live under the generic settings API:\n * - `GET /api/admin/settings/media.imageStyles` — Read current styles\n * - `PATCH /api/admin/settings/media.imageStyles` — Update styles (Zod-validated)\n *\n * Routes handled by generic entity handler (via fallthrough):\n * - `PATCH /api/admin/media/:id` — Update metadata with translation support\n */\nexport function mediaRoutes(): AdminRoute {\n return {\n prefix: 'media',\n resource: 'media',\n actions: ['view', 'create', 'update', 'delete'],\n handlers: {\n GET: handleGet,\n POST: handlePost,\n DELETE: handleDelete,\n },\n }\n}\n","/**\n * Media plugin — auto-registers the Media entity, mounts admin routes, and\n * contributes sidebar + default-route scaffolding for the admin shell.\n *\n * @example\n * ```typescript\n * import { media } from '@murumets-ee/media/plugin'\n *\n * export default defineLumiConfig({\n * plugins: [\n * storage(),\n * media({ maxUploadSize: 10 * 1024 * 1024 }),\n * ],\n * })\n * ```\n */\n\nimport type { Plugin, PluginSettingsDefinition } from '@murumets-ee/core'\n// Self-reference the `./image-styles` subpath (not the internal source\n// files) so the plugin bundle externalizes the React components instead\n// of inlining them — the subpath is built separately with a `'use client'`\n// banner, and Next.js needs to see that boundary preserved.\nimport { ImageStylesManager, RegenerateVariantsAction } from '@murumets-ee/media/image-styles'\nimport { mediaRoutes } from './admin/routes.js'\nimport { Media } from './entity.js'\nimport { imageStylesSettings } from './image-styles-settings.js'\nimport type { MediaPluginConfig } from './types.js'\n\nlet _mediaConfig: Required<MediaPluginConfig> | null = null\n\n/**\n * Get the resolved media plugin configuration.\n * Throws if plugin not initialized.\n */\nexport function getMediaConfig(): Required<MediaPluginConfig> {\n if (!_mediaConfig) {\n throw new Error('@murumets-ee/media plugin not initialized. Add media() to your plugins array.')\n }\n return _mediaConfig\n}\n\n/**\n * Media plugin factory.\n *\n * - Registers the Media entity\n * - Mounts the media admin API routes\n * - Contributes sidebar + default-route metadata\n * - Validates that @murumets-ee/storage + @murumets-ee/settings are registered at init\n * - Captures resolved configuration for `getMediaConfig()`\n */\nexport function media(config?: MediaPluginConfig): Plugin {\n const resolvedConfig: Required<MediaPluginConfig> = {\n acceptedTypes: config?.acceptedTypes ?? ['image/*', 'video/*', 'audio/*', 'application/pdf'],\n maxUploadSize: config?.maxUploadSize ?? 50 * 1024 * 1024,\n defaultVisibility: config?.defaultVisibility ?? 'public',\n imageStyles: config?.imageStyles ?? {\n thumbnail: { width: 200, height: 200, fit: 'cover', format: 'webp', quality: 80 },\n },\n }\n\n return {\n name: '@murumets-ee/media',\n shared: {\n // Self-contributes the media.imageStyles namespace. The merge engine\n // auto-derives the permission resource (`settings:media.imageStyles`)\n // and the sidebar entry under \"Settings\" group; the settings plugin's\n // init hook picks it up for route dispatch. Apps don't have to wire\n // anything — adding `media()` to plugins is enough.\n settings: [imageStylesSettings as PluginSettingsDefinition],\n },\n server: {\n entities: [Media],\n routes: [mediaRoutes()],\n init: async (app) => {\n if (!app.plugins.has('@murumets-ee/storage')) {\n throw new Error(\n '@murumets-ee/media requires @murumets-ee/storage plugin. ' +\n 'Add storage() before media() in your plugins array.',\n )\n }\n\n if (!app.plugins.has('@murumets-ee/settings')) {\n throw new Error(\n '@murumets-ee/media requires @murumets-ee/settings plugin. ' +\n 'Add settings() before media() in your plugins array.',\n )\n }\n\n _mediaConfig = resolvedConfig\n\n // Image style defaults live in the plugin config and are exposed via\n // `getMediaConfig()`. Persistent overrides go to the settings DB\n // through the generic settings API at `/api/admin/settings/media.imageStyles`\n // — see `image-styles-settings.ts`. `resolveImageStyles` reads\n // DB-first, config-fallback.\n //\n // We deliberately do NOT seed the DB here. Init must stay lightweight:\n // it runs in every context (Next.js server, Next.js build, CLI commands).\n // The prior eager-seed path pulled in `@murumets-ee/settings`'s main entry —\n // which carries `import 'server-only'` — and crashed non-RSC Node bootstrap.\n\n app.logger.info(\n {\n acceptedTypes: resolvedConfig.acceptedTypes,\n maxUploadSize: resolvedConfig.maxUploadSize,\n defaultVisibility: resolvedConfig.defaultVisibility,\n },\n 'Media plugin initialized',\n )\n },\n },\n adminUi: {\n sidebar: [\n {\n id: 'media',\n group: 'Library',\n label: 'Media',\n href: '/admin/media',\n iconName: 'image',\n },\n ],\n defaultRoutes: [\n {\n path: 'media',\n factory: 'MediaListPage',\n nav: { label: 'Media', iconName: 'image', group: 'Library' },\n },\n {\n path: 'media/[id]',\n factory: 'MediaEditPage',\n },\n ],\n // Self-contributes the rich image-styles editor and the\n // \"Regenerate All Variants\" action. Apps don't have to wire either\n // — they appear automatically on /admin/settings/media.imageStyles\n // (route + sidebar entry auto-derived from `shared.settings`).\n settingRenderers: {\n 'media.imageStyles': ImageStylesManager,\n },\n settingsActions: {\n 'media.imageStyles': RegenerateVariantsAction,\n },\n },\n }\n}\n"],"mappings":"+MA+BA,MAAM,EAAU,kEAEhB,SAAS,EAAY,EAA4C,CAC/D,OAAO,IAAU,IAAA,IAAa,EAAQ,KAAK,EAAM,CAenD,IAAI,EAAiH,KAErH,eAAe,GAAa,CAU1B,MATA,CACE,KAAkB,SAAY,CAC5B,GAAM,CAAE,UAAW,MAAM,OAAO,qBAC1B,CAAE,uBAAwB,MAAM,OAAO,wBACvC,CAAE,oBAAqB,MAAM,OAAO,+BACpC,EAAM,GAAQ,CACpB,OAAO,EAAoB,GAAkB,CAAE,CAAE,MAAK,CAAC,IACrD,CAEC,EAGT,eAAe,GAAkC,CAC/C,GAAM,CAAE,qBAAsB,MAAM,OAAO,6BACrC,CAAE,eAAgB,MAAM,OAAO,gBAC/B,CAAE,SAAU,MAAM,OAAO,yBAAA,KAAA,GAAA,EAAA,EAAA,CACzB,EAAU,MAAM,GAAY,CAElC,OAAO,IAAI,EAAY,CAAE,MADX,EAAkB,EACF,CAAE,UAAS,CAAC,CAO5C,SAAS,EAAK,EAAe,EAAS,IAAK,CACzC,OAAO,IAAI,SAAS,KAAK,UAAU,EAAK,CAAE,CACxC,SACA,QAAS,CAAE,eAAgB,mBAAoB,CAChD,CAAC,CAGJ,SAAS,EAAU,EAAiB,EAAgB,CAClD,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AAS,CACP,CACE,GAAI,QACJ,MAAO,UACP,MAAO,QACP,KAAM,eACN,SAAU,QACX,CACF,CACD,cAAe,CACb,CACE,KAAM,QACN,QAAS,gBACT,IAAK,CAAE,MAAO,QAAS,SAAU,QAAS,MAAO,UAAW,CAC7D,CACD,CACE,KAAM,aACN,QAAS,gBACV,CACF,CAKD,iBAAkB,CAChB,oBAAqB,EACtB,CACD,gBAAiB,CACf,oBAAqB,EACtB,CACF,CACF"}
1
+ {"version":3,"file":"plugin.mjs","names":[],"sources":["../src/admin/routes.ts","../src/plugin.ts"],"sourcesContent":["/**\n * Media admin routes — one static `defineAdminRoute` per HTTP method.\n *\n * **URL surface served by this module:**\n *\n * - GET /api/admin/media — list with search/filter + URLs\n * - GET /api/admin/media/<id> — single record with URL\n * - GET /api/admin/media/<id>/usage — entities referencing this media\n * - POST /api/admin/media — upload (multipart FormData)\n * - POST /api/admin/media/regenerate-variants — bulk variant regeneration\n * - DELETE /api/admin/media/<id> — delete + storage cleanup\n *\n * Standard entity CRUD (PATCH with translations) falls through to the\n * generic entity handler — add `Media` to `entities` in your handler config.\n *\n * **Why per-method `defineAdminRoute`** (vs. the previous top-level\n * `resource: 'media'` + auto-mapped permission):\n *\n * - The wrapper (`guardedHandler` from `@murumets-ee/core`) owns the\n * permission gate, `permission.denied` audit, and 403 body shape\n * uniformly with every other migrated plugin. The previous shape\n * relied on `METHOD_TO_ACTION` auto-mapping at the api-handler\n * dispatch level which couldn't emit per-route audit metadata.\n * - Inline `if (!checkPermission('media', 'create')) ...` defenses\n * at the regenerate-variants / upload / delete branches are now\n * redundant — the wrapper enforces the permission BEFORE the\n * handler runs.\n *\n * **`matchAnyPath` rationale:** media's URL surface predates the\n * static-second-segment convention every other plugin follows\n * (`/taxonomy/<vocab>/<id>`, `/settings/<namespace>/<rest>`). The\n * second segment under `/media` is the media id itself — a runtime\n * UUID — which the dispatcher's literal `segments[0]` match would\n * miss for every request. The catch-all flag declares \"this entry\n * claims every (prefix, method) sub-path no other entry matched\" so\n * the existing URL contract works under the per-method dispatch\n * model. Static POST sub-paths (`regenerate-variants`) take\n * precedence over the catch-all entry on POST. See\n * `DefineAdminRouteSpec.matchAnyPath` in `@murumets-ee/core` for the\n * full contract.\n *\n * **Default roles:** broad for view (`['admin', 'editor', 'agent',\n * 'viewer']`), narrower for writes (`['admin', 'editor']`).\n * Conservative starting point — apps can grant more via the\n * Permissions UI.\n *\n * @example\n * ```typescript\n * import { createAdminApiHandler } from '@murumets-ee/admin-ui/server'\n * import { mediaRoutes } from '@murumets-ee/media/admin'\n * import { Media } from '@murumets-ee/media'\n *\n * const handler = createAdminApiHandler({\n * authenticate: async (req) => { ... },\n * entities: [Article, Media],\n * routes: [...mediaRoutes()],\n * })\n * ```\n */\n\nimport {\n type AdminRoute,\n type AdminRouteHandler,\n combineAdminRoutes,\n defineAdminRoute,\n safeAudit,\n} from '@murumets-ee/core'\nimport type { MediaClient } from '../client.js'\nimport type { MediaPickerItem, MediaPickerListResult } from '../picker/types.js'\n\n// ---------------------------------------------------------------------------\n// Validation\n// ---------------------------------------------------------------------------\n\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i\n\nfunction isValidUuid(value: string | undefined): value is string {\n return value !== undefined && UUID_RE.test(value)\n}\n\n/**\n * Closed enum of allowed `mediaType` filter values, in lockstep with the\n * `mediaType` field on the Media entity. The list MUST match\n * `MediaListOptions.mediaType` (declared in `../types.js`) — TypeScript\n * doesn't link the two automatically, so the small drift risk is\n * accepted in exchange for not pulling a runtime dep on the entity\n * schema package just to read its enum.\n *\n * Used as both the runtime allowlist (`isAllowedMediaType`) and the\n * source of truth for the narrowed type the guard produces — keeping\n * `as` casts off the handler's hot path.\n */\nconst ALLOWED_MEDIA_TYPES = ['image', 'video', 'audio', 'document', 'other'] as const\ntype AllowedMediaType = (typeof ALLOWED_MEDIA_TYPES)[number]\n\nfunction isAllowedMediaType(value: string): value is AllowedMediaType {\n // Cast to readonly string[] so the typed-tuple `includes` check works\n // with an arbitrary string input — `Array.prototype.includes`'s\n // signature on a typed tuple only accepts members of the tuple\n // (TS 4.9+ literal-narrowing), which is exactly what we want to\n // sidestep here.\n return (ALLOWED_MEDIA_TYPES as readonly string[]).includes(value)\n}\n\n/**\n * Hard cap on the `offset` query param. The dispatcher's allowed-pages\n * model is `limit ∈ [1, 100]`; even with the max page size that's\n * 1000 pages before hitting MAX_OFFSET, which is well beyond any\n * realistic admin-UI scroll depth. Forces slow-discard offset attacks\n * (`?offset=999999999`) to revert to a sane upper bound. Cursor-based\n * pagination would let this go higher, but the media list is\n * offset-based by convention with the entity-list shell.\n */\nconst MAX_OFFSET = 100_000\n\n/**\n * Strict non-negative integer parser for query params.\n *\n * `Number(raw)` silently coerces blanks (`'' → 0`), hex (`'0x05' → 5`),\n * exponent notation (`'1e2' → 100`), and signed (`'+5'/'-5'`) values —\n * all of which pass a downstream `Number.isInteger(n) && n >= 0` check.\n * Pre-filtering with `/^\\d+$/` keeps the contract honest: \"if you don't\n * send a pure non-negative integer string, you get the default.\" Same\n * pattern as `packages/taxonomy/src/admin/routes.ts:handleGet` tree\n * branch from PR-C-taxonomy.\n */\nfunction parseUintParam(raw: string | null, fallback: number): number {\n if (raw === null || !/^\\d+$/.test(raw)) return fallback\n const parsed = Number(raw)\n // The regex above stops hex / exponent / signed / whitespace / blank\n // inputs, but a long digit-only string still slips past — `Number(...)`\n // returns `Infinity` past ~309 digits, and precision is lost past\n // 2^53. Both would propagate through `client.findMany`'s\n // `offset: parsed` into a Postgres query that either crashes the\n // driver (`Infinity` is not a valid bigint) or silently rounds (the\n // 2^53 precision-loss boundary). Reject via `Number.isSafeInteger`\n // so overflowing inputs revert to `fallback` like every other\n // malformed value.\n if (!Number.isSafeInteger(parsed)) return fallback\n return parsed\n}\n\n// ---------------------------------------------------------------------------\n// Response helpers\n// ---------------------------------------------------------------------------\n\nfunction jsonResponse(data: unknown, status = 200): Response {\n return new Response(JSON.stringify(data), {\n status,\n headers: { 'Content-Type': 'application/json' },\n })\n}\n\nfunction jsonError(message: string, status: number): Response {\n return jsonResponse({ error: message }, status)\n}\n\n// ---------------------------------------------------------------------------\n// Per-request MediaClient factory + cached storage client\n// ---------------------------------------------------------------------------\n//\n// MediaClient and its AdminClient MUST be built per-request — AdminClient's\n// context resolver is captured eagerly at construction (see\n// buildContextResolver in @murumets-ee/core/clients). A module-level singleton\n// would bake the first request's user + tenant scope into every subsequent\n// request's writes — a cross-request permission/scope leak.\n//\n// Storage config is process-global and safe to cache once.\n\ntype StorageClient = Awaited<ReturnType<typeof import('@murumets-ee/storage').createStorageClient>>\n\ninterface StorageState {\n clientPromise: Promise<StorageClient> | null\n}\n\n// Module-level state. `null` once eviction fires on a rejection so the next\n// request gets a fresh resolution attempt (see `getStorage`'s `.catch`).\nconst storageState: StorageState = { clientPromise: null }\n\n/**\n * Resolve the process-wide storage client. The pending-promise slot is\n * cleared on rejection so a transient `createStorageClient` failure\n * (DB hiccup, misconfig) doesn't poison every subsequent media request\n * for the lifetime of the Node process. Same pattern as\n * `packages/taxonomy/src/admin/routes.ts:getClient` from PR-C-taxonomy.\n */\nasync function getStorage(): Promise<StorageClient> {\n if (!storageState.clientPromise) {\n const pending = (async () => {\n const { getApp } = await import('@murumets-ee/core')\n const { createStorageClient } = await import('@murumets-ee/storage')\n const { getStorageConfig } = await import('@murumets-ee/storage/plugin')\n const app = getApp()\n return createStorageClient(getStorageConfig(), { app })\n })()\n // Clear the slot on rejection so a transient failure doesn't poison\n // every subsequent request. `pending.catch(handler)` attaches a\n // synchronous rejection listener that resets the cached slot — the\n // handler returns `undefined`, NOT a re-throw — so the new\n // `.catch`-returned promise resolves, but we never await or hold\n // that promise. The ORIGINAL `pending` (stored in\n // `storageState.clientPromise`) is what callers `await`, and it's\n // still in its rejected state — so the caller observing this\n // resolution sees the underlying error. The `.catch` also marks\n // the rejection as \"handled\" for Node's unhandled-rejection\n // tracker. `storageState.clientPromise` holds the original `pending`\n // so concurrent in-flight callers share one resolution.\n pending.catch(() => {\n if (storageState.clientPromise === pending) storageState.clientPromise = null\n })\n storageState.clientPromise = pending\n }\n return storageState.clientPromise\n}\n\nasync function getMediaClient(): Promise<MediaClient> {\n const { createAdminClient } = await import('@murumets-ee/core/clients')\n const { MediaClient } = await import('../client.js')\n const { Media } = await import('../entity.js')\n const storage = await getStorage()\n const admin = createAdminClient(Media)\n return new MediaClient({ admin, storage })\n}\n\n// ---------------------------------------------------------------------------\n// Handlers\n// ---------------------------------------------------------------------------\n\nconst handleGet: AdminRouteHandler = async (req, ctx) => {\n const { isStorageConfigured, getStorageConfigReason } = await import('@murumets-ee/storage')\n const segments = ctx.segments\n\n // GET /media/<id>/usage — DB-only lookup, safe even when storage is\n // unconfigured. Validate the UUID first so a malformed id 400s\n // uniformly with the storage-configured branch below.\n if (segments.length === 2 && segments[1] === 'usage') {\n const id = segments[0]\n if (!isValidUuid(id)) return jsonError('Invalid media ID format', 400)\n\n const { findMediaUsages } = await import('../usage.js')\n const { getApp } = await import('@murumets-ee/core')\n const app = getApp()\n const usages = await findMediaUsages(id, app)\n return jsonResponse({ usages })\n }\n\n // Reject unknown sub-paths explicitly. The wrapper-gate has already\n // passed (caller has `media:view`); a handler-level 404 here matches\n // the dispatcher's miss-shape so unknown URLs don't fall through to\n // the single-id branch and 400/500 with a misleading reason. The\n // only valid 2-segment URL is `<id>/usage`, which was already\n // claimed by the early-return above — anything else with >=2\n // segments is not a recognized media route.\n if (segments.length >= 2) return jsonError('Not found', 404)\n\n // GET /media/<id> — validate UUID up front so a bad request still\n // 400s when storage happens to be unconfigured (matches DELETE).\n const singleId = segments.length > 0 ? segments[0] : undefined\n if (singleId !== undefined && !isValidUuid(singleId)) {\n return jsonError('Invalid media ID format', 400)\n }\n\n // Everything below needs a working storage client. If env isn't\n // wired, return a structured \"disabled\" response rather than 500 —\n // the media list page renders a banner and new admins can finish\n // onboarding without being blocked on a crash loop.\n if (!isStorageConfigured()) {\n const reason = getStorageConfigReason() ?? 'Storage not configured'\n if (segments.length > 0) {\n // Single item — treat as not-found-ish to avoid leaking\n // existence; include reason so the UI can surface it.\n return jsonResponse({ error: reason, configured: false, reason }, 503)\n }\n // GET /media — empty list + disabled flag for the picker's banner.\n const response: MediaPickerListResult & { configured: false; reason: string } = {\n items: [],\n total: 0,\n configured: false,\n reason,\n }\n return jsonResponse(response)\n }\n\n const client = await getMediaClient()\n\n // GET /media/<id> — single item with URL (full record for EntityForm + picker)\n if (singleId !== undefined) {\n const record = await client.findById(singleId)\n if (!record) return jsonError('Media not found', 404)\n\n const url = await client.getUrl(singleId)\n return jsonResponse({ ...record, url })\n }\n\n // GET /media — list with search/filter + batch URL resolution\n const url = new URL(req.url)\n const search = url.searchParams.get('search') ?? undefined\n // mediaType MUST be validated against the entity's closed enum before\n // it reaches `client.findMany` — the previous shape force-cast the raw\n // query value with `as 'image' | ...` which is a type-system lie. A\n // bogus value like `?mediaType=bogus` would parameterize into\n // `WHERE media_type = 'bogus'` (no SQL injection — Drizzle is\n // parameterized — but the row count is silently zero, which is\n // confusing). Empty string from `?mediaType=` is also passed-through\n // by the prior `?? undefined` shape since empty string is not null.\n // Allowlist + type guard drops bogus / empty values cleanly so the\n // filter is omitted instead of applied with a no-match value.\n const rawMediaType = url.searchParams.get('mediaType')\n const mediaType =\n rawMediaType !== null && isAllowedMediaType(rawMediaType) ? rawMediaType : undefined\n // Strict parsing keeps the contract honest — see `parseUintParam`\n // JSDoc. Cap limit to [1, 100] and offset to [0, MAX_OFFSET] so a\n // request can't ask for an unboundedly large page nor force a\n // slow-discard scan with `?offset=99999999`.\n const limit = Math.min(Math.max(parseUintParam(url.searchParams.get('limit'), 24), 1), 100)\n const offset = Math.min(parseUintParam(url.searchParams.get('offset'), 0), MAX_OFFSET)\n\n const result = await client.findMany({\n ...(search !== undefined && { search }),\n ...(mediaType !== undefined && { mediaType }),\n limit,\n offset,\n })\n\n // Resolve original URLs + thumbnail variant URLs for all items.\n const ids = result.items.map((item) => item.id)\n const [urlMap, thumbMap] = await Promise.all([\n client.getUrls(ids),\n client.getVariantUrls(ids, 'thumbnail'),\n ])\n\n const items: (MediaPickerItem & { thumbnailUrl?: string })[] = result.items.map((item) => {\n const thumbnailUrl = thumbMap.get(item.id)\n return {\n id: item.id,\n title: item.title ?? null,\n alt: item.alt ?? null,\n filename: item.filename,\n mimeType: item.mimeType,\n size: item.size,\n mediaType: item.mediaType,\n url: urlMap.get(item.id) ?? '',\n ...(thumbnailUrl !== undefined && { thumbnailUrl }),\n width: item.width ?? null,\n height: item.height ?? null,\n }\n })\n\n const response: MediaPickerListResult = { items, total: result.total }\n return jsonResponse(response)\n}\n\nconst handleUpload: AdminRouteHandler = async (req, ctx) => {\n const { isStorageConfigured, getStorageConfigReason, detectMimeType } = await import(\n '@murumets-ee/storage'\n )\n\n // Upload is registered at `path: ''` (NOT matchAnyPath) — the\n // dispatcher only invokes this handler when segments=[]. The api-\n // handler ALSO rejects empty/whitespace-only first segments with a\n // 400 before any plugin dispatcher runs (see\n // `packages/admin-ui/src/server/api-handler/index.ts` segment-\n // validation block). So this guard is defense-in-depth — per HANDOFF\n // §\"Defense-in-depth `&& segments[i]` guards are fine\" — protecting\n // against a future framework invariant change that lets a non-empty\n // segment reach a `path: ''` static entry.\n if (ctx.segments.length > 0) return jsonError('Not found', 404)\n\n if (!isStorageConfigured()) {\n return jsonError(getStorageConfigReason() ?? 'Storage not configured', 503)\n }\n\n const client = await getMediaClient()\n\n const formData = await req.formData()\n const file = formData.get('file')\n // FormData `get` returns string | File | null. Reject anything that\n // isn't a File so the typed `file.size`/`file.arrayBuffer()` below\n // is safe without a runtime cast.\n if (!(file instanceof File) || file.size === 0) {\n return jsonError('No file provided', 400)\n }\n\n // Guard against oversized uploads (50 MB limit). Hardcoded rather\n // than read from getMediaConfig() to keep this handler independent\n // of plugin-init order — the plugin's resolved config may not be\n // populated yet under CLI / non-RSC startup paths.\n const MAX_UPLOAD_SIZE = 50 * 1024 * 1024\n if (file.size > MAX_UPLOAD_SIZE) {\n return jsonError(\n `File too large: ${(file.size / 1024 / 1024).toFixed(1)} MB exceeds 50 MB limit`,\n 400,\n )\n }\n\n const buffer = Buffer.from(await file.arrayBuffer())\n\n // Detect actual MIME type from file content (prevents spoofing).\n const { mimeType, mismatch } = await detectMimeType(\n buffer,\n file.type || 'application/octet-stream',\n )\n if (mismatch) {\n return jsonError(\n `File content doesn't match declared type: claimed ${file.type}, detected ${mimeType}`,\n 400,\n )\n }\n\n const result = await client.upload(buffer, {\n filename: file.name,\n mimeType,\n size: file.size,\n uploadedBy: ctx.user.id,\n })\n\n const item: MediaPickerItem = {\n id: result.media.id,\n title: result.media.title ?? null,\n alt: result.media.alt ?? null,\n filename: result.media.filename,\n mimeType: result.media.mimeType,\n size: result.media.size,\n mediaType: result.media.mediaType,\n url: result.url,\n width: result.media.width ?? null,\n height: result.media.height ?? null,\n }\n\n safeAudit(ctx, {\n action: 'media.upload',\n entityType: 'media',\n entityId: result.media.id,\n userId: ctx.user.id,\n ...(ctx.user.name !== undefined && { userName: ctx.user.name }),\n changes: {\n filename: result.media.filename,\n mimeType: result.media.mimeType,\n size: result.media.size,\n mediaType: result.media.mediaType,\n },\n })\n\n return jsonResponse(item, 201)\n}\n\nconst handleRegenerateVariants: AdminRouteHandler = async (_req, ctx) => {\n const { isStorageConfigured, getStorageConfigReason } = await import('@murumets-ee/storage')\n\n // Static POST path='regenerate-variants' — the dispatcher only invokes\n // this handler when `segments[0] === 'regenerate-variants'`. Trailing\n // segments (e.g. POST /media/regenerate-variants/extra) aren't a\n // supported sub-route.\n if (ctx.segments.length !== 1) return jsonError('Not found', 404)\n\n if (!isStorageConfigured()) {\n return jsonError(getStorageConfigReason() ?? 'Storage not configured', 503)\n }\n\n const { regenerateAllVariants } = await import('../regenerate-variants.js')\n const { getApp, getContext } = await import('@murumets-ee/core')\n const { resolveImageStyles } = await import('../resolve-image-styles.js')\n const { createStorageClient } = await import('@murumets-ee/storage')\n const { getStorageConfig } = await import('@murumets-ee/storage/plugin')\n\n const app = getApp()\n const styles = await resolveImageStyles(app, app.logger)\n if (!styles || Object.keys(styles).length === 0) {\n return jsonError('No image styles configured', 400)\n }\n\n const storageConfig = getStorageConfig()\n const storage = createStorageClient(storageConfig, { app })\n\n const result = await regenerateAllVariants({\n app,\n storage,\n logger: app.logger.child({ media: true }),\n styles,\n contextResolver: () => {\n const requestCtx = getContext()\n if (!requestCtx?.user || !requestCtx?.checker) return undefined\n return {\n user: requestCtx.user,\n checker: requestCtx.checker,\n ...(requestCtx.scope !== undefined && { scope: requestCtx.scope }),\n }\n },\n })\n\n safeAudit(ctx, {\n action: 'media.regenerate_variants',\n userId: ctx.user.id,\n ...(ctx.user.name !== undefined && { userName: ctx.user.name }),\n metadata: { total: result.total, processed: result.processed, errors: result.errors },\n })\n\n return jsonResponse(result)\n}\n\nconst handleDelete: AdminRouteHandler = async (_req, ctx) => {\n const segments = ctx.segments\n\n // DELETE /media — no id supplied. Reject as 400, NOT 404, so a\n // caller confusing \"no id\" with \"id not found\" gets a meaningful\n // error. The wrapper-gate has already validated the caller has\n // media:delete, so the 400 isn't an information-disclosure vector.\n if (segments.length === 0) return jsonError('Media ID required', 400)\n\n // Reject sub-paths beyond /<id> — DELETE /media/<id>/usage etc.\n if (segments.length > 1) return jsonError('Not found', 404)\n\n const id = segments[0]\n if (!isValidUuid(id)) return jsonError('Invalid media ID format', 400)\n\n const { isStorageConfigured, getStorageConfigReason } = await import('@murumets-ee/storage')\n if (!isStorageConfigured()) {\n // Can't safely delete — MediaClient needs storage to remove the\n // actual object, and partial delete (DB row gone, object orphaned)\n // would leak storage. Surface the reason so the UI can display it.\n return jsonError(getStorageConfigReason() ?? 'Storage not configured', 503)\n }\n\n // AdminClient.delete() checks entity_refs and throws\n // ReferencedEntityError if this media is still referenced. The\n // error bubbles to the caller's error handler which returns 409\n // with usage details.\n const client = await getMediaClient()\n await client.delete(id)\n\n safeAudit(ctx, {\n action: 'media.delete',\n entityType: 'media',\n entityId: id,\n userId: ctx.user.id,\n ...(ctx.user.name !== undefined && { userName: ctx.user.name }),\n })\n\n return jsonResponse({ deleted: 1 })\n}\n\n// ---------------------------------------------------------------------------\n// Route factory\n// ---------------------------------------------------------------------------\n\n/**\n * Default roles for view: broad reach across the admin shell.\n *\n * `BUILT_IN_ROLES` in `packages/auth/src/permissions.ts` is exactly\n * `['admin', 'public', 'authenticated', 'agent']` — `admin` is\n * hardcoded as an unconditional yes in `buildPermissionChecker`,\n * `agent` is the only non-admin built-in that flows through\n * `buildInitialRoleDefinitions()` + `upsertBuiltInRoles`. The\n * `agent` entry in this list is what gives ops agents read-only\n * media access on first boot of a fresh install.\n *\n * `editor` and `viewer` are CONVENTIONAL app-defined roles —\n * apps that follow the scaffold pattern create them as part of\n * their own role catalog. Including them in `defaultRoles` doesn't\n * seed them (the seeder only iterates the built-ins above), but\n * the values DO flow into the process-local permission catalog\n * (see `registerPermission` in `@murumets-ee/core`), which the\n * forthcoming Permission Matrix UI (PR-D) reads to show \"this\n * route's recommended default grants\" against the app's actual\n * role set. The catalog is also the mechanism via which a future\n * upgrade of `upsertBuiltInRoles` could extend the seed surface\n * to app-defined roles without each plugin having to re-declare\n * its defaults.\n */\nconst VIEW_DEFAULT_ROLES = ['admin', 'editor', 'agent', 'viewer'] as const\n\n/** Default roles for create/delete — narrower than view. */\nconst WRITE_DEFAULT_ROLES = ['admin', 'editor'] as const\n\n/**\n * Build admin API routes for media management.\n *\n * Returns `AdminRoute[]` from `combineAdminRoutes` — one entry per\n * `(prefix, method)` after grouping. Callers spread the result into\n * their top-level routes list: `routes: [...mediaRoutes()]`.\n *\n * Four `defineAdminRoute` entries:\n *\n * - GET matchAnyPath with `media:view` defaultRoles: VIEW_DEFAULT_ROLES\n * - POST path='' `media:create` defaultRoles: WRITE_DEFAULT_ROLES\n * - POST path='regenerate-variants' `media:create` defaultRoles: WRITE_DEFAULT_ROLES\n * - DELETE matchAnyPath with `media:delete` defaultRoles: WRITE_DEFAULT_ROLES\n *\n * Permissions are auto-registered by the entity catalog\n * (`buildResourceCatalog` in `@murumets-ee/auth`) AND by\n * `registerPermission` inside `defineAdminRoute`. Idempotent —\n * `registerPermission` unions `defaultRoles` on repeat registration,\n * so the framework's two pathways agree on the final grant set.\n *\n * Standard entity CRUD (PATCH with translations) is NOT registered\n * here — it falls through to the generic entity handler. Add `Media`\n * to the `entities` array in your handler config to enable it.\n */\nexport function mediaRoutes(): AdminRoute[] {\n const entries = [\n defineAdminRoute({\n prefix: 'media',\n path: '',\n method: 'GET',\n permission: 'media:view',\n defaultRoles: VIEW_DEFAULT_ROLES,\n matchAnyPath: true,\n description: 'Read media — list, single item, or referencing-entity usage report.',\n handler: handleGet,\n }),\n defineAdminRoute({\n prefix: 'media',\n path: '',\n method: 'POST',\n permission: 'media:create',\n defaultRoles: WRITE_DEFAULT_ROLES,\n description: 'Upload a media file (multipart FormData with `file` field).',\n handler: handleUpload,\n }),\n defineAdminRoute({\n prefix: 'media',\n path: 'regenerate-variants',\n method: 'POST',\n permission: 'media:create',\n defaultRoles: WRITE_DEFAULT_ROLES,\n description: 'Regenerate every image-style variant for every media row.',\n handler: handleRegenerateVariants,\n }),\n defineAdminRoute({\n prefix: 'media',\n path: '',\n method: 'DELETE',\n permission: 'media:delete',\n defaultRoles: WRITE_DEFAULT_ROLES,\n matchAnyPath: true,\n description: 'Delete a media record + its storage object.',\n handler: handleDelete,\n }),\n ]\n\n return combineAdminRoutes(entries)\n}\n","/**\n * Media plugin — auto-registers the Media entity, mounts admin routes, and\n * contributes sidebar + default-route scaffolding for the admin shell.\n *\n * @example\n * ```typescript\n * import { media } from '@murumets-ee/media/plugin'\n *\n * export default defineLumiConfig({\n * plugins: [\n * storage(),\n * media({ maxUploadSize: 10 * 1024 * 1024 }),\n * ],\n * })\n * ```\n */\n\nimport { definePlugin } from '@murumets-ee/core'\n// Self-reference the `./image-styles` subpath (not the internal source\n// files) so the plugin bundle externalizes the React components instead\n// of inlining them — the subpath is built separately with a `'use client'`\n// banner, and Next.js needs to see that boundary preserved.\nimport { ImageStylesManager, RegenerateVariantsAction } from '@murumets-ee/media/image-styles'\nimport { mediaRoutes } from './admin/routes.js'\nimport { Media } from './entity.js'\nimport { imageStylesSettings } from './image-styles-settings.js'\nimport type { MediaPluginConfig } from './types.js'\n\nlet _mediaConfig: Required<MediaPluginConfig> | null = null\n\n/**\n * Get the resolved media plugin configuration.\n * Throws if plugin not initialized.\n */\nexport function getMediaConfig(): Required<MediaPluginConfig> {\n if (!_mediaConfig) {\n throw new Error('@murumets-ee/media plugin not initialized. Add media() to your plugins array.')\n }\n return _mediaConfig\n}\n\n/**\n * Media plugin factory.\n *\n * - Registers the Media entity\n * - Mounts the media admin API routes\n * - Contributes sidebar + default-route metadata\n * - Validates that @murumets-ee/storage + @murumets-ee/settings are registered at init\n * - Captures resolved configuration for `getMediaConfig()`\n */\nexport function media(config?: MediaPluginConfig) {\n const resolvedConfig: Required<MediaPluginConfig> = {\n acceptedTypes: config?.acceptedTypes ?? ['image/*', 'video/*', 'audio/*', 'application/pdf'],\n maxUploadSize: config?.maxUploadSize ?? 50 * 1024 * 1024,\n defaultVisibility: config?.defaultVisibility ?? 'public',\n imageStyles: config?.imageStyles ?? {\n thumbnail: { width: 200, height: 200, fit: 'cover', format: 'webp', quality: 80 },\n },\n }\n\n return definePlugin({\n name: '@murumets-ee/media',\n shared: {\n // Self-contributes the media.imageStyles namespace. The merge engine\n // auto-derives the permission resource (`settings_media.imageStyles`)\n // and the sidebar entry under the \"Settings\" group. The app's\n // admin-api-handler call site aggregates plugin-contributed\n // namespaces into `settingsRoutes(...)` (see admin-playground's\n // `getAllSettings()` for the canonical pattern); apps that follow\n // the scaffold pattern get this for free.\n // Drop the `as PluginSettingsDefinition` cast — it would widen the\n // namespace literal (e.g. `'media.imageStyles'`) to `string`,\n // leaking `settings_${string}:view|update` into the resolved\n // permission union via `<const N>` capture loss.\n // `imageStylesSettings` is structurally a superset of\n // `PluginSettingsDefinition` (full vs. narrow `SettingsDefinition`),\n // which TS accepts directly. The `readonly` outer tuple comes from\n // the parent definePlugin's `<const S>` capture.\n settings: [imageStylesSettings],\n },\n server: {\n entities: [Media],\n routes: [...mediaRoutes()],\n init: async (app) => {\n if (!app.plugins.has('@murumets-ee/storage')) {\n throw new Error(\n '@murumets-ee/media requires @murumets-ee/storage plugin. ' +\n 'Add storage() before media() in your plugins array.',\n )\n }\n\n if (!app.plugins.has('@murumets-ee/settings')) {\n throw new Error(\n '@murumets-ee/media requires @murumets-ee/settings plugin. ' +\n 'Add settings() before media() in your plugins array.',\n )\n }\n\n _mediaConfig = resolvedConfig\n\n // Image style defaults live in the plugin config and are exposed via\n // `getMediaConfig()`. Persistent overrides go to the settings DB\n // through the generic settings API at `/api/admin/settings/media.imageStyles`\n // — see `image-styles-settings.ts`. `resolveImageStyles` reads\n // DB-first, config-fallback.\n //\n // We deliberately do NOT seed the DB here. Init must stay lightweight:\n // it runs in every context (Next.js server, Next.js build, CLI commands).\n // The prior eager-seed path pulled in `@murumets-ee/settings`'s main entry —\n // which carries `import 'server-only'` — and crashed non-RSC Node bootstrap.\n\n app.logger.info(\n {\n acceptedTypes: resolvedConfig.acceptedTypes,\n maxUploadSize: resolvedConfig.maxUploadSize,\n defaultVisibility: resolvedConfig.defaultVisibility,\n },\n 'Media plugin initialized',\n )\n },\n },\n adminUi: {\n sidebar: [\n {\n id: 'media',\n group: 'Library',\n label: 'Media',\n href: '/admin/media',\n iconName: 'image',\n },\n ],\n defaultRoutes: [\n {\n path: 'media',\n factory: 'MediaListPage',\n nav: { label: 'Media', iconName: 'image', group: 'Library' },\n },\n {\n path: 'media/[id]',\n factory: 'MediaEditPage',\n },\n ],\n // Self-contributes the rich image-styles editor and the\n // \"Regenerate All Variants\" action. Apps don't have to wire either\n // — they appear automatically on /admin/settings/media.imageStyles\n // (route + sidebar entry auto-derived from `shared.settings`).\n settingRenderers: {\n 'media.imageStyles': ImageStylesManager,\n },\n settingsActions: {\n 'media.im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,cAAe,GAAQ,eAAiB,GAAK,KAAO,KACpD,kBAAmB,GAAQ,mBAAqB,SAChD,YAAa,GAAQ,aAAe,CAClC,UAAW,CAAE,MAAO,IAAK,OAAQ,IAAK,IAAK,QAAS,OAAQ,OAAQ,QAAS,GAAI,CAClF,CACF,CAED,OAAO,EAAa,CAClB,KAAM,qBACN,OAAQ,CAgBN,SAAU,CAAC,EAAoB,CAChC,CACD,OAAQ,CACN,SAAU,CAAC,EAAM,CACjB,OAAQ,CAAC,GAAG,GAAa,CAAC,CAC1B,KAAM,KAAO,IAAQ,CACnB,GAAI,CAAC,EAAI,QAAQ,IAAI,uBAAuB,CAC1C,MAAU,MACR,+GAED,CAGH,GAAI,CAAC,EAAI,QAAQ,IAAI,wBAAwB,CAC3C,MAAU,MACR,iHAED,CAGH,EAAe,EAaf,EAAI,OAAO,KACT,CACE,cAAe,EAAe,cAC9B,cAAe,EAAe,cAC9B,kBAAmB,EAAe,kBACnC,CACD,2BACD,EAEJ,CACD,QAAS,CACP,QAAS,CACP,CACE,GAAI,QACJ,MAAO,UACP,MAAO,QACP,KAAM,eACN,SAAU,QACX,CACF,CACD,cAAe,CACb,CACE,KAAM,QACN,QAAS,gBACT,IAAK,CAAE,MAAO,QAAS,SAAU,QAAS,MAAO,UAAW,CAC7D,CACD,CACE,KAAM,aACN,QAAS,gBACV,CACF,CAKD,iBAAkB,CAChB,oBAAqB,EACtB,CACD,gBAAiB,CACf,oBAAqB,EACtB,CACF,CACF,CAAC"}
@@ -1,4 +1,4 @@
1
- import { t as ImageStyle } from "./types-BMW3aeEB.mjs";
1
+ import { t as ImageStyle } from "./types-CqjShq2U.mjs";
2
2
 
3
3
  //#region src/process-image.d.ts
4
4
  /** Result of processing an image through Sharp */
@@ -1,4 +1,4 @@
1
- import { a as MediaRecord, l as Media } from "./types-BMW3aeEB.mjs";
1
+ import { a as MediaRecord, l as Media } from "./types-CqjShq2U.mjs";
2
2
  import { CountOptions, FindByIdOptions, FindManyOptions, QueryClient } from "@murumets-ee/entity/query";
3
3
 
4
4
  //#region src/query-client.d.ts
@@ -0,0 +1,2 @@
1
+ import{i as e,r as t,t as n}from"./variant-key-gVMhzKyv.mjs";import"server-only";async function r(r){let{app:i,storage:a,logger:o,styles:s}=r,c=i.db.readWrite,{AdminClient:l}=await import(`@murumets-ee/entity/admin`),{Media:u}=await import(`./entity-D1YaFEh8.mjs`).then(e=>e.n),{schemaRegistry:d}=await import(`@murumets-ee/db`),{eq:f}=await import(`drizzle-orm`),p=new l({entity:u,db:c,logger:o,contextResolver:r.contextResolver}),m=d.get(`media`);if(!m)throw Error(`Media schema not registered`);let h={total:0,processed:0,skipped:0,errors:0},g=0;for(o?.info({styles:Object.keys(s)},`Starting variant regeneration`);;){let r=await p.findMany({where:f(m.mediaType,`image`),limit:100,offset:g});if(r.length===0)break;h.total+=r.length;for(let i of r)try{if(!t(i.mimeType)){h.skipped++;continue}let r=await a.download(i.fileKey),c;if(Buffer.isBuffer(r.body))c=r.body;else{let e=[],t=r.body.getReader();for(;;){let{done:n,value:r}=await t.read();if(n)break;r&&e.push(r)}c=Buffer.concat(e)}let l=await e(c,s),u=await a.getMetadata(i.fileKey),d=u?.metadata?.variants;d&&await Promise.all(Object.values(d).map(e=>a.delete(e).catch(()=>{})));let f={},p=u?.visibility??`public`,m=await Promise.all([...l.variants].map(async([e,t])=>{let r=n(i.fileKey,e,t.format);try{return await a.upload(t.buffer,{key:r,filename:`${e}_${i.filename}`,mimeType:t.mimeType,size:t.buffer.byteLength,visibility:p,metadata:{variantOf:i.fileKey,style:e}}),{styleName:e,vKey:r,ok:!0}}catch(t){return o?.warn({style:e,key:r,error:t},`Failed to upload regenerated variant (non-fatal)`),{styleName:e,vKey:r,ok:!1}}}));for(let e of m)e.ok&&(f[e.styleName]=e.vKey);Object.keys(f).length>0&&await a.updateMetadata(i.fileKey,{metadata:{...u?.metadata??{},variants:f}}).catch(e=>{o?.warn({key:i.fileKey,error:e},`Failed to update variant metadata (non-fatal)`)}),h.processed++,o?.debug({id:i.id,variants:Object.keys(f)},`Regenerated variants`)}catch(e){h.errors++,o?.error({id:i.id,fileKey:i.fileKey,error:e},`Failed to regenerate variants for media record`)}if(g+=100,r.length<100)break}return o?.info(h,`Variant regeneration complete`),h}export{r as regenerateAllVariants};
2
+ //# sourceMappingURL=regenerate-variants-DJIFSrdC.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"regenerate-variants-DJIFSrdC.mjs","names":[],"sources":["../src/regenerate-variants.ts"],"sourcesContent":["/**\n * Batch variant regeneration — reprocesses all image media with updated styles.\n *\n * Downloads each original from storage, generates new variants via Sharp,\n * cleans up old variant files, and uploads new ones.\n *\n * Per-image errors are logged but don't stop the batch.\n */\n\nimport 'server-only'\n\nimport type { Logger, ToolkitApp } from '@murumets-ee/core'\nimport type { ContextResolver } from '@murumets-ee/entity'\nimport type { StorageClient } from '@murumets-ee/storage'\nimport { isProcessableImage, processImage } from './process-image.js'\nimport type { ImageStyle } from './types.js'\nimport { deriveVariantKey } from './variant-key.js'\n\nconst BATCH_SIZE = 100\n\nexport interface RegenerateOptions {\n /** Toolkit app (provides db). */\n app: ToolkitApp\n storage: StorageClient\n logger?: Logger\n /** Current image styles to generate */\n styles: Record<string, ImageStyle>\n /** Security context resolver — passed through to AdminClient. */\n contextResolver?: ContextResolver\n}\n\nexport interface RegenerateResult {\n /** Total image media records found */\n total: number\n /** Successfully reprocessed */\n processed: number\n /** Skipped (non-processable mimeType, download failed, etc.) */\n skipped: number\n /** Failed with errors */\n errors: number\n}\n\n/**\n * Regenerate variants for all image media.\n * Processes in batches of 100 to avoid memory pressure.\n */\nexport async function regenerateAllVariants(options: RegenerateOptions): Promise<RegenerateResult> {\n const { app, storage, logger, styles } = options\n const db = app.db.readWrite\n const { AdminClient } = await import('@murumets-ee/entity/admin')\n const { Media } = await import('./entity.js')\n const { schemaRegistry } = await import('@murumets-ee/db')\n const { eq } = await import('drizzle-orm')\n\n const admin = new AdminClient<typeof Media.allFields>({\n entity: Media,\n db,\n logger,\n contextResolver: options.contextResolver,\n })\n const table = schemaRegistry.get('media')\n if (!table) throw new Error('Media schema not registered')\n\n const result: RegenerateResult = { total: 0, processed: 0, skipped: 0, errors: 0 }\n let offset = 0\n\n logger?.info({ styles: Object.keys(styles) }, 'Starting variant regeneration')\n\n // Process in batches\n while (true) {\n const batch = await admin.findMany({\n where: eq(table.mediaType, 'image'),\n limit: BATCH_SIZE,\n offset,\n })\n\n if (batch.length === 0) break\n result.total += batch.length\n\n for (const record of batch) {\n try {\n // Skip non-processable images (SVG, GIF)\n if (!isProcessableImage(record.mimeType)) {\n result.skipped++\n continue\n }\n\n // Download original from storage\n const downloaded = await storage.download(record.fileKey)\n let buffer: Buffer\n if (Buffer.isBuffer(downloaded.body)) {\n buffer = downloaded.body\n } else {\n // ReadableStream → Buffer\n const chunks: Uint8Array[] = []\n const reader = downloaded.body.getReader()\n while (true) {\n const { done, value } = await reader.read()\n if (done) break\n if (value) chunks.push(value)\n }\n buffer = Buffer.concat(chunks)\n }\n\n // Generate new variants\n const processed = await processImage(buffer, styles)\n\n // Delete old variant files (best-effort, parallel)\n const oldFileRecord = await storage.getMetadata(record.fileKey)\n const oldVariants = (oldFileRecord?.metadata as Record<string, unknown> | null)?.variants as\n | Record<string, string>\n | undefined\n if (oldVariants) {\n await Promise.all(\n Object.values(oldVariants).map((vKey) => storage.delete(vKey).catch(() => {})),\n )\n }\n\n // Upload new variants (parallel)\n const newVariantKeys: Record<string, string> = {}\n const visibility = oldFileRecord?.visibility ?? 'public'\n const uploadResults = await Promise.all(\n [...processed.variants].map(async ([styleName, variant]) => {\n const vKey = deriveVariantKey(record.fileKey, styleName, variant.format)\n try {\n await storage.upload(variant.buffer, {\n key: vKey,\n filename: `${styleName}_${record.filename}`,\n mimeType: variant.mimeType,\n size: variant.buffer.byteLength,\n visibility,\n metadata: { variantOf: record.fileKey, style: styleName },\n })\n return { styleName, vKey, ok: true as const }\n } catch (uploadErr) {\n logger?.warn(\n { style: styleName, key: vKey, error: uploadErr },\n 'Failed to upload regenerated variant (non-fatal)',\n )\n return { styleName, vKey, ok: false as const }\n }\n }),\n )\n for (const r of uploadResults) {\n if (r.ok) newVariantKeys[r.styleName] = r.vKey\n }\n\n // Update original file's metadata with new variant keys\n if (Object.keys(newVariantKeys).length > 0) {\n await storage\n .updateMetadata(record.fileKey, {\n metadata: {\n ...(oldFileRecord?.metadata ?? {}),\n variants: newVariantKeys,\n },\n })\n .catch((metaErr: unknown) => {\n logger?.warn(\n { key: record.fileKey, error: metaErr },\n 'Failed to update variant metadata (non-fatal)',\n )\n })\n }\n\n result.processed++\n logger?.debug(\n { id: record.id, variants: Object.keys(newVariantKeys) },\n 'Regenerated variants',\n )\n } catch (err) {\n result.errors++\n logger?.error(\n { id: record.id, fileKey: record.fileKey, error: err },\n 'Failed to regenerate variants for media record',\n )\n }\n }\n\n offset += BATCH_SIZE\n if (batch.length < BATCH_SIZE) break\n }\n\n logger?.info(result, 'Variant regeneration complete')\n return result\n}\n"],"mappings":"iFA8CA,eAAsB,EAAsB,EAAuD,CACjG,GAAM,CAAE,MAAK,UAAS,SAAQ,UAAW,EACnC,EAAK,EAAI,GAAG,UACZ,CAAE,eAAgB,MAAM,OAAO,6BAC/B,CAAE,SAAU,MAAM,OAAO,yBAAA,KAAA,GAAA,EAAA,EAAA,CACzB,CAAE,kBAAmB,MAAM,OAAO,mBAClC,CAAE,MAAO,MAAM,OAAO,eAEtB,EAAQ,IAAI,EAAoC,CACpD,OAAQ,EACR,KACA,SACA,gBAAiB,EAAQ,gBAC1B,CAAC,CACI,EAAQ,EAAe,IAAI,QAAQ,CACzC,GAAI,CAAC,EAAO,MAAU,MAAM,8BAA8B,CAE1D,IAAM,EAA2B,CAAE,MAAO,EAAG,UAAW,EAAG,QAAS,EAAG,OAAQ,EAAG,CAC9E,EAAS,EAKb,IAHA,GAAQ,KAAK,CAAE,OAAQ,OAAO,KAAK,EAAO,CAAE,CAAE,gCAAgC,GAGjE,CACX,IA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I,GAAe,OACtC,EAAW,CAKlB,OAJA,GAAQ,KACN,CAAE,MAAO,EAAW,IAAK,EAAM,MAAO,EAAW,CACjD,mDACD,CACM,CAAE,YAAW,OAAM,GAAI,GAAgB,GAEhD,CACH,CACD,IAAK,IAAM,KAAK,EACV,EAAE,KAAI,EAAe,EAAE,WAAa,EAAE,MAIxC,OAAO,KAAK,EAAe,CAAC,OAAS,GACvC,MAAM,EACH,eAAe,EAAO,QAAS,CAC9B,SAAU,CACR,GAAI,GAAe,UAAY,EAAE,CACjC,SAAU,EACX,CACF,CAAC,CACD,MAAO,GAAqB,CAC3B,GAAQ,KACN,CAAE,IAAK,EAAO,QAAS,MAAO,EAAS,CACvC,gDACD,EACD,CAGN,EAAO,YACP,GAAQ,MACN,CAAE,GAAI,EAAO,GAAI,SAAU,OAAO,KAAK,EAAe,CAAE,CACxD,uBACD,OACM,EAAK,CACZ,EAAO,SACP,GAAQ,MACN,CAAE,GAAI,EAAO,GAAI,QAAS,EAAO,QAAS,MAAO,EAAK,CACtD,iDACD,CAKL,GADA,GAAU,IACN,EAAM,OAAS,IAAY,MAIjC,OADA,GAAQ,KAAK,EAAQ,gCAAgC,CAC9C"}
@@ -0,0 +1,2 @@
1
+ import{n as e,r as t,t as n}from"./variant-key-CFr3fR-n.mjs";import"server-only";async function r(r){let{app:i,storage:a,logger:o,styles:s}=r,c=i.db.readWrite,{AdminClient:l}=await import(`@murumets-ee/entity/admin`),{Media:u}=await import(`./entity-B75A4L3p.mjs`),{schemaRegistry:d}=await import(`@murumets-ee/db`),{eq:f}=await import(`drizzle-orm`),p=new l({entity:u,db:c,logger:o,contextResolver:r.contextResolver}),m=d.get(`media`);if(!m)throw Error(`Media schema not registered`);let h={total:0,processed:0,skipped:0,errors:0},g=0;for(o?.info({styles:Object.keys(s)},`Starting variant regeneration`);;){let r=await p.findMany({where:f(m.mediaType,`image`),limit:100,offset:g});if(r.length===0)break;h.total+=r.length;for(let i of r)try{if(!e(i.mimeType)){h.skipped++;continue}let r=await a.download(i.fileKey),c;if(Buffer.isBuffer(r.body))c=r.body;else{let e=[],t=r.body.getReader();for(;;){let{done:n,value:r}=await t.read();if(n)break;r&&e.push(r)}c=Buffer.concat(e)}let l=await t(c,s),u=await a.getMetadata(i.fileKey),d=u?.metadata?.variants;d&&await Promise.all(Object.values(d).map(e=>a.delete(e).catch(()=>{})));let f={},p=u?.visibility??`public`,m=await Promise.all([...l.variants].map(async([e,t])=>{let r=n(i.fileKey,e,t.format);try{return await a.upload(t.buffer,{key:r,filename:`${e}_${i.filename}`,mimeType:t.mimeType,size:t.buffer.byteLength,visibility:p,metadata:{variantOf:i.fileKey,style:e}}),{styleName:e,vKey:r,ok:!0}}catch(t){return o?.warn({style:e,key:r,error:t},`Failed to upload regenerated variant (non-fatal)`),{styleName:e,vKey:r,ok:!1}}}));for(let e of m)e.ok&&(f[e.styleName]=e.vKey);Object.keys(f).length>0&&await a.updateMetadata(i.fileKey,{metadata:{...u?.metadata??{},variants:f}}).catch(e=>{o?.warn({key:i.fileKey,error:e},`Failed to update variant metadata (non-fatal)`)}),h.processed++,o?.debug({id:i.id,variants:Object.keys(f)},`Regenerated variants`)}catch(e){h.errors++,o?.error({id:i.id,fileKey:i.fileKey,error:e},`Failed to regenerate variants for media record`)}if(g+=100,r.length<100)break}return o?.info(h,`Variant regeneration complete`),h}export{r as regenerateAllVariants};
2
+ //# sourceMappingURL=regenerate-variants-DtA5pKjj.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"regenerate-variants-DtA5pKjj.mjs","names":[],"sources":["../src/regenerate-variants.ts"],"sourcesContent":["/**\n * Batch variant regeneration — reprocesses all image media with updated styles.\n *\n * Downloads each original from storage, generates new variants via Sharp,\n * cleans up old variant files, and uploads new ones.\n *\n * Per-image errors are logged but don't stop the batch.\n */\n\nimport 'server-only'\n\nimport type { Logger, ToolkitApp } from '@murumets-ee/core'\nimport type { ContextResolver } from '@murumets-ee/entity'\nimport type { StorageClient } from '@murumets-ee/storage'\nimport { isProcessableImage, processImage } from './process-image.js'\nimport type { ImageStyle } from './types.js'\nimport { deriveVariantKey } from './variant-key.js'\n\nconst BATCH_SIZE = 100\n\nexport interface RegenerateOptions {\n /** Toolkit app (provides db). */\n app: ToolkitApp\n storage: StorageClient\n logger?: Logger\n /** Current image styles to generate */\n styles: Record<string, ImageStyle>\n /** Security context resolver — passed through to AdminClient. */\n contextResolver?: ContextResolver\n}\n\nexport interface RegenerateResult {\n /** Total image media records found */\n total: number\n /** Successfully reprocessed */\n processed: number\n /** Skipped (non-processable mimeType, download failed, etc.) */\n skipped: number\n /** Failed with errors */\n errors: number\n}\n\n/**\n * Regenerate variants for all image media.\n * Processes in batches of 100 to avoid memory pressure.\n */\nexport async function regenerateAllVariants(options: RegenerateOptions): Promise<RegenerateResult> {\n const { app, storage, logger, styles } = options\n const db = app.db.readWrite\n const { AdminClient } = await import('@murumets-ee/entity/admin')\n const { Media } = await import('./entity.js')\n const { schemaRegistry } = await import('@murumets-ee/db')\n const { eq } = await import('drizzle-orm')\n\n const admin = new AdminClient<typeof Media.allFields>({\n entity: Media,\n db,\n logger,\n contextResolver: options.contextResolver,\n })\n const table = schemaRegistry.get('media')\n if (!table) throw new Error('Media schema not registered')\n\n const result: RegenerateResult = { total: 0, processed: 0, skipped: 0, errors: 0 }\n let offset = 0\n\n logger?.info({ styles: Object.keys(styles) }, 'Starting variant regeneration')\n\n // Process in batches\n while (true) {\n const batch = await admin.findMany({\n where: eq(table.mediaType, 'image'),\n limit: BATCH_SIZE,\n offset,\n })\n\n if (batch.length === 0) break\n result.total += batch.length\n\n for (const record of batch) {\n try {\n // Skip non-processable images (SVG, GIF)\n if (!isProcessableImage(record.mimeType)) {\n result.skipped++\n continue\n }\n\n // Download original from storage\n const downloaded = await storage.download(record.fileKey)\n let buffer: Buffer\n if (Buffer.isBuffer(downloaded.body)) {\n buffer = downloaded.body\n } else {\n // ReadableStream → Buffer\n const chunks: Uint8Array[] = []\n const reader = downloaded.body.getReader()\n while (true) {\n const { done, value } = await reader.read()\n if (done) break\n if (value) chunks.push(value)\n }\n buffer = Buffer.concat(chunks)\n }\n\n // Generate new variants\n const processed = await processImage(buffer, styles)\n\n // Delete old variant files (best-effort, parallel)\n const oldFileRecord = await storage.getMetadata(record.fileKey)\n const oldVariants = (oldFileRecord?.metadata as Record<string, unknown> | null)?.variants as\n | Record<string, string>\n | undefined\n if (oldVariants) {\n await Promise.all(\n Object.values(oldVariants).map((vKey) => storage.delete(vKey).catch(() => {})),\n )\n }\n\n // Upload new variants (parallel)\n const newVariantKeys: Record<string, string> = {}\n const visibility = oldFileRecord?.visibility ?? 'public'\n const uploadResults = await Promise.all(\n [...processed.variants].map(async ([styleName, variant]) => {\n const vKey = deriveVariantKey(record.fileKey, styleName, variant.format)\n try {\n await storage.upload(variant.buffer, {\n key: vKey,\n filename: `${styleName}_${record.filename}`,\n mimeType: variant.mimeType,\n size: variant.buffer.byteLength,\n visibility,\n metadata: { variantOf: record.fileKey, style: styleName },\n })\n return { styleName, vKey, ok: true as const }\n } catch (uploadErr) {\n logger?.warn(\n { style: styleName, key: vKey, error: uploadErr },\n 'Failed to upload regenerated variant (non-fatal)',\n )\n return { styleName, vKey, ok: false as const }\n }\n }),\n )\n for (const r of uploadResults) {\n if (r.ok) newVariantKeys[r.styleName] = r.vKey\n }\n\n // Update original file's metadata with new variant keys\n if (Object.keys(newVariantKeys).length > 0) {\n await storage\n .updateMetadata(record.fileKey, {\n metadata: {\n ...(oldFileRecord?.metadata ?? {}),\n variants: newVariantKeys,\n },\n })\n .catch((metaErr: unknown) => {\n logger?.warn(\n { key: record.fileKey, error: metaErr },\n 'Failed to update variant metadata (non-fatal)',\n )\n })\n }\n\n result.processed++\n logger?.debug(\n { id: record.id, variants: Object.keys(newVariantKeys) },\n 'Regenerated variants',\n )\n } catch (err) {\n result.errors++\n logger?.error(\n { id: record.id, fileKey: record.fileKey, error: err },\n 'Failed to regenerate variants for media record',\n )\n }\n }\n\n offset += BATCH_SIZE\n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,EAAO,GAAI,QAAS,EAAO,QAAS,MAAO,EAAK,CACtD,iDACD,CAKL,GADA,GAAU,IACN,EAAM,OAAS,IAAY,MAIjC,OADA,GAAQ,KAAK,EAAQ,gCAAgC,CAC9C"}
@@ -1,2 +1,2 @@
1
- const e={thumbnail:{width:200,height:200,fit:`cover`,format:`webp`,quality:80}};async function t(t,n){try{let{createSettingsClient:e}=await import(`@murumets-ee/settings`),{imageStylesSettings:n}=await import(`./image-styles-settings-B4QOt7Ve.mjs`),r=await e(n,{app:t}).get(`imageStyles`);if(r&&Object.keys(r).length>0)return r}catch(e){n?.warn({err:e},`resolveImageStyles: settings DB read failed — falling back`)}try{let{getMediaConfig:e}=await import(`./plugin-DZaF1BHS.mjs`);return e().imageStyles}catch{}return e}export{t as resolveImageStyles};
2
- //# sourceMappingURL=resolve-image-styles-2sa0O7wU.mjs.map
1
+ const e={thumbnail:{width:200,height:200,fit:`cover`,format:`webp`,quality:80}};async function t(t,n){try{let{createSettingsClient:e}=await import(`@murumets-ee/settings`),{imageStylesSettings:n}=await import(`./image-styles-settings-B4QOt7Ve.mjs`),r=await e(n,{app:t}).get(`imageStyles`);if(r&&Object.keys(r).length>0)return r}catch(e){n?.warn({err:e},`resolveImageStyles: settings DB read failed — falling back`)}try{let{getMediaConfig:e}=await import(`./plugin-BPabn1pf.mjs`);return e().imageStyles}catch{}return e}export{t as resolveImageStyles};
2
+ //# sourceMappingURL=resolve-image-styles-Dqaa5QsX.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"resolve-image-styles-2sa0O7wU.mjs","names":[],"sources":["../src/resolve-image-styles.ts"],"sourcesContent":["/**\n * Image style resolution waterfall — single source of truth for the\n * \"which styles should we use?\" question.\n *\n * Priority: settings DB (user-configured) → plugin config (from `media()`\n * factory call) → hardcoded defaults (thumbnail only).\n *\n * This replaces three near-duplicate blocks (MediaClient's private\n * resolveImageStyles + two admin-route branches) that had drifted — the\n * routes didn't treat an empty stored object as \"fall back to config\"\n * while MediaClient did. Consolidating here keeps the behavior consistent\n * and logs the DB read failure so operators can diagnose issues instead\n * of silently getting defaults.\n *\n * Not cached. MediaClient wraps this with its own per-instance cache.\n */\n\nimport type { Logger, ToolkitApp } from '@murumets-ee/core'\nimport type { ImageStyle } from './types.js'\n\nconst HARDCODED_DEFAULTS: Record<string, ImageStyle> = {\n thumbnail: { width: 200, height: 200, fit: 'cover', format: 'webp', quality: 80 },\n}\n\nexport async function resolveImageStyles(\n app: ToolkitApp,\n logger?: Logger,\n): Promise<Record<string, ImageStyle>> {\n // 1. Settings DB (source of truth once the admin UI has saved anything).\n // An empty record counts as \"nothing configured\" — fall through. This\n // matches the pre-extraction behavior of MediaClient and fixes the\n // routes' prior behavior of showing an empty UI in that case.\n try {\n const { createSettingsClient } = await import('@murumets-ee/settings')\n const { imageStylesSettings } = await import('./image-styles-settings.js')\n const settingsClient = createSettingsClient(imageStylesSettings, { app })\n const stored = await settingsClient.get('imageStyles')\n if (stored && Object.keys(stored).length > 0) return stored\n } catch (err) {\n // Logging matters: prior silent catches masked real issues (e.g. DB\n // unavailable) as \"no styles\" and routed admins toward config fallback\n // when the real failure was infrastructure.\n logger?.warn({ err }, 'resolveImageStyles: settings DB read failed — falling back')\n }\n\n // 2. Plugin config (from the `media()` factory call in lumi.config.ts).\n try {\n const { getMediaConfig } = await import('./plugin.js')\n return getMediaConfig().imageStyles\n } catch {\n // Plugin not initialized (e.g. unit tests that don't call media()) —\n // fall through to hardcoded defaults. No log: this is a valid mode.\n }\n\n // 3. Hardcoded baseline — a single thumbnail style so uploads don't fail\n // in a toolkit that never registered the plugin.\n return HARDCODED_DEFAULTS\n}\n"],"mappings":"AAoBA,MAAM,EAAiD,CACrD,UAAW,CAAE,MAAO,IAAK,OAAQ,IAAK,IAAK,QAAS,OAAQ,OAAQ,QAAS,GAAI,CAClF,CAED,eAAsB,EACpB,EACA,EACqC,CAKrC,GAAI,CACF,GAAM,CAAE,wBAAyB,MAAM,OAAO,yBACxC,CAAE,uBAAwB,MAAM,OAAO,wCAEvC,EAAS,MADQ,EAAqB,EAAqB,CAAE,MAAK,CACrC,CAAC,IAAI,cAAc,CACtD,GAAI,GAAU,OAAO,KAAK,EAAO,CAAC,OAAS,EAAG,OAAO,QAC9C,EAAK,CAIZ,GAAQ,KAAK,CAAE,MAAK,CAAE,6DAA6D,CAIrF,GAAI,CACF,GAAM,CAAE,kBAAmB,MAAM,OAAO,yBACxC,OAAO,GAAgB,CAAC,iBAClB,EAOR,OAAO"}
1
+ {"version":3,"file":"resolve-image-styles-Dqaa5QsX.mjs","names":[],"sources":["../src/resolve-image-styles.ts"],"sourcesContent":["/**\n * Image style resolution waterfall — single source of truth for the\n * \"which styles should we use?\" question.\n *\n * Priority: settings DB (user-configured) → plugin config (from `media()`\n * factory call) → hardcoded defaults (thumbnail only).\n *\n * This replaces three near-duplicate blocks (MediaClient's private\n * resolveImageStyles + two admin-route branches) that had drifted — the\n * routes didn't treat an empty stored object as \"fall back to config\"\n * while MediaClient did. Consolidating here keeps the behavior consistent\n * and logs the DB read failure so operators can diagnose issues instead\n * of silently getting defaults.\n *\n * Not cached. MediaClient wraps this with its own per-instance cache.\n */\n\nimport type { Logger, ToolkitApp } from '@murumets-ee/core'\nimport type { ImageStyle } from './types.js'\n\nconst HARDCODED_DEFAULTS: Record<string, ImageStyle> = {\n thumbnail: { width: 200, height: 200, fit: 'cover', format: 'webp', quality: 80 },\n}\n\nexport async function resolveImageStyles(\n app: ToolkitApp,\n logger?: Logger,\n): Promise<Record<string, ImageStyle>> {\n // 1. Settings DB (source of truth once the admin UI has saved anything).\n // An empty record counts as \"nothing configured\" — fall through. This\n // matches the pre-extraction behavior of MediaClient and fixes the\n // routes' prior behavior of showing an empty UI in that case.\n try {\n const { createSettingsClient } = await import('@murumets-ee/settings')\n const { imageStylesSettings } = await import('./image-styles-settings.js')\n const settingsClient = createSettingsClient(imageStylesSettings, { app })\n const stored = await settingsClient.get('imageStyles')\n if (stored && Object.keys(stored).length > 0) return stored\n } catch (err) {\n // Logging matters: prior silent catches masked real issues (e.g. DB\n // unavailable) as \"no styles\" and routed admins toward config fallback\n // when the real failure was infrastructure.\n logger?.warn({ err }, 'resolveImageStyles: settings DB read failed — falling back')\n }\n\n // 2. Plugin config (from the `media()` factory call in lumi.config.ts).\n try {\n const { getMediaConfig } = await import('./plugin.js')\n return getMediaConfig().imageStyles\n } catch {\n // Plugin not initialized (e.g. unit tests that don't call media()) —\n // fall through to hardcoded defaults. No log: this is a valid mode.\n }\n\n // 3. Hardcoded baseline — a single thumbnail style so uploads don't fail\n // in a toolkit that never registered the plugin.\n return HARDCODED_DEFAULTS\n}\n"],"mappings":"AAoBA,MAAM,EAAiD,CACrD,UAAW,CAAE,MAAO,IAAK,OAAQ,IAAK,IAAK,QAAS,OAAQ,OAAQ,QAAS,GAAI,CAClF,CAED,eAAsB,EACpB,EACA,EACqC,CAKrC,GAAI,CACF,GAAM,CAAE,wBAAyB,MAAM,OAAO,yBACxC,CAAE,uBAAwB,MAAM,OAAO,wCAEvC,EAAS,MADQ,EAAqB,EAAqB,CAAE,MAAK,CACrC,CAAC,IAAI,cAAc,CACtD,GAAI,GAAU,OAAO,KAAK,EAAO,CAAC,OAAS,EAAG,OAAO,QAC9C,EAAK,CAIZ,GAAQ,KAAK,CAAE,MAAK,CAAE,6DAA6D,CAIrF,GAAI,CACF,GAAM,CAAE,kBAAmB,MAAM,OAAO,yBACxC,OAAO,GAAgB,CAAC,iBAClB,EAOR,OAAO"}
@@ -0,0 +1,2 @@
1
+ import{combineAdminRoutes as e,defineAdminRoute as t,safeAudit as n}from"@murumets-ee/core";const r=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function i(e){return e!==void 0&&r.test(e)}const a=[`image`,`video`,`audio`,`document`,`other`];function o(e){return a.includes(e)}function s(e,t){if(e===null||!/^\d+$/.test(e))return t;let n=Number(e);return Number.isSafeInteger(n)?n:t}function c(e,t=200){return new Response(JSON.stringify(e),{status:t,headers:{"Content-Type":`application/json`}})}function l(e,t){return c({error:e},t)}const u={clientPromise:null};async function d(){if(!u.clientPromise){let e=(async()=>{let{getApp:e}=await import(`@murumets-ee/core`),{createStorageClient:t}=await import(`@murumets-ee/storage`),{getStorageConfig:n}=await import(`@murumets-ee/storage/plugin`),r=e();return t(n(),{app:r})})();e.catch(()=>{u.clientPromise===e&&(u.clientPromise=null)}),u.clientPromise=e}return u.clientPromise}async function f(){let{createAdminClient:e}=await import(`@murumets-ee/core/clients`),{MediaClient:t}=await import(`./client-BcA8CDBk.mjs`),{Media:n}=await import(`./entity-B75A4L3p.mjs`),r=await d();return new t({admin:e(n),storage:r})}const p=async(e,t)=>{let{isStorageConfigured:n,getStorageConfigReason:r}=await import(`@murumets-ee/storage`),a=t.segments;if(a.length===2&&a[1]===`usage`){let e=a[0];if(!i(e))return l(`Invalid media ID format`,400);let{findMediaUsages:t}=await import(`./usage-BwUdYWkA.mjs`),{getApp:n}=await import(`@murumets-ee/core`);return c({usages:await t(e,n())})}if(a.length>=2)return l(`Not found`,404);let u=a.length>0?a[0]:void 0;if(u!==void 0&&!i(u))return l(`Invalid media ID format`,400);if(!n()){let e=r()??`Storage not configured`;return a.length>0?c({error:e,configured:!1,reason:e},503):c({items:[],total:0,configured:!1,reason:e})}let d=await f();if(u!==void 0){let e=await d.findById(u);if(!e)return l(`Media not found`,404);let t=await d.getUrl(u);return c({...e,url:t})}let p=new URL(e.url),m=p.searchParams.get(`search`)??void 0,h=p.searchParams.get(`mediaType`),g=h!==null&&o(h)?h:void 0,_=Math.min(Math.max(s(p.searchParams.get(`limit`),24),1),100),v=Math.min(s(p.searchParams.get(`offset`),0),1e5),y=await d.findMany({...m!==void 0&&{search:m},...g!==void 0&&{mediaType:g},limit:_,offset:v}),b=y.items.map(e=>e.id),[x,S]=await Promise.all([d.getUrls(b),d.getVariantUrls(b,`thumbnail`)]);return c({items:y.items.map(e=>{let t=S.get(e.id);return{id:e.id,title:e.title??null,alt:e.alt??null,filename:e.filename,mimeType:e.mimeType,size:e.size,mediaType:e.mediaType,url:x.get(e.id)??``,...t!==void 0&&{thumbnailUrl:t},width:e.width??null,height:e.height??null}}),total:y.total})},m=async(e,t)=>{let{isStorageConfigured:r,getStorageConfigReason:i,detectMimeType:a}=await import(`@murumets-ee/storage`);if(t.segments.length>0)return l(`Not found`,404);if(!r())return l(i()??`Storage not configured`,503);let o=await f(),s=(await e.formData()).get(`file`);if(!(s instanceof File)||s.size===0)return l(`No file provided`,400);if(s.size>50*1024*1024)return l(`File too large: ${(s.size/1024/1024).toFixed(1)} MB exceeds 50 MB limit`,400);let u=Buffer.from(await s.arrayBuffer()),{mimeType:d,mismatch:p}=await a(u,s.type||`application/octet-stream`);if(p)return l(`File content doesn't match declared type: claimed ${s.type}, detected ${d}`,400);let m=await o.upload(u,{filename:s.name,mimeType:d,size:s.size,uploadedBy:t.user.id}),h={id:m.media.id,title:m.media.title??null,alt:m.media.alt??null,filename:m.media.filename,mimeType:m.media.mimeType,size:m.media.size,mediaType:m.media.mediaType,url:m.url,width:m.media.width??null,height:m.media.height??null};return n(t,{action:`media.upload`,entityType:`media`,entityId:m.media.id,userId:t.user.id,...t.user.name!==void 0&&{userName:t.user.name},changes:{filename:m.media.filename,mimeType:m.media.mimeType,size:m.media.size,mediaType:m.media.mediaType}}),c(h,201)},h=async(e,t)=>{let{isStorageConfigured:r,getStorageConfigReason:i}=await import(`@murumets-ee/storage`);if(t.segments.length!==1)return l(`Not found`,404);if(!r())return l(i()??`Storage not configured`,503);let{regenerateAllVariants:a}=await import(`./regenerate-variants-DtA5pKjj.mjs`),{getApp:o,getContext:s}=await import(`@murumets-ee/core`),{resolveImageStyles:u}=await import(`./resolve-image-styles-Dqaa5QsX.mjs`),{createStorageClient:d}=await import(`@murumets-ee/storage`),{getStorageConfig:f}=await import(`@murumets-ee/storage/plugin`),p=o(),m=await u(p,p.logger);if(!m||Object.keys(m).length===0)return l(`No image styles configured`,400);let h=await a({app:p,storage:d(f(),{app:p}),logger:p.logger.child({media:!0}),styles:m,contextResolver:()=>{let e=s();if(!(!e?.user||!e?.checker))return{user:e.user,checker:e.checker,...e.scope!==void 0&&{scope:e.scope}}}});return n(t,{action:`media.regenerate_variants`,userId:t.user.id,...t.user.name!==void 0&&{userName:t.user.name},metadata:{total:h.total,processed:h.processed,errors:h.errors}}),c(h)},g=async(e,t)=>{let r=t.segments;if(r.length===0)return l(`Media ID required`,400);if(r.length>1)return l(`Not found`,404);let a=r[0];if(!i(a))return l(`Invalid media ID format`,400);let{isStorageConfigured:o,getStorageConfigReason:s}=await import(`@murumets-ee/storage`);return o()?(await(await f()).delete(a),n(t,{action:`media.delete`,entityType:`media`,entityId:a,userId:t.user.id,...t.user.name!==void 0&&{userName:t.user.name}}),c({deleted:1})):l(s()??`Storage not configured`,503)},_=[`admin`,`editor`,`agent`,`viewer`],v=[`admin`,`editor`];function y(){return e([t({prefix:`media`,path:``,method:`GET`,permission:`media:view`,defaultRoles:_,matchAnyPath:!0,description:`Read media — list, single item, or referencing-entity usage report.`,handler:p}),t({prefix:`media`,path:``,method:`POST`,permission:`media:create`,defaultRoles:v,description:"Upload a media file (multipart FormData with `file` field).",handler:m}),t({prefix:`media`,path:`regenerate-variants`,method:`POST`,permission:`media:create`,defaultRoles:v,description:`Regenerate every image-style variant for every media row.`,handler:h}),t({prefix:`media`,path:``,method:`DELETE`,permission:`media:delete`,defaultRoles:v,matchAnyPath:!0,description:`Delete a media record + its storage object.`,handler:g})])}export{y as t};
2
+ //# sourceMappingURL=routes-tHvb9cgv.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"routes-tHvb9cgv.mjs","names":[],"sources":["../src/admin/routes.ts"],"sourcesContent":["/**\n * Media admin routes — one static `defineAdminRoute` per HTTP method.\n *\n * **URL surface served by this module:**\n *\n * - GET /api/admin/media — list with search/filter + URLs\n * - GET /api/admin/media/<id> — single record with URL\n * - GET /api/admin/media/<id>/usage — entities referencing this media\n * - POST /api/admin/media — upload (multipart FormData)\n * - POST /api/admin/media/regenerate-variants — bulk variant regeneration\n * - DELETE /api/admin/media/<id> — delete + storage cleanup\n *\n * Standard entity CRUD (PATCH with translations) falls through to the\n * generic entity handler — add `Media` to `entities` in your handler config.\n *\n * **Why per-method `defineAdminRoute`** (vs. the previous top-level\n * `resource: 'media'` + auto-mapped permission):\n *\n * - The wrapper (`guardedHandler` from `@murumets-ee/core`) owns the\n * permission gate, `permission.denied` audit, and 403 body shape\n * uniformly with every other migrated plugin. The previous shape\n * relied on `METHOD_TO_ACTION` auto-mapping at the api-handler\n * dispatch level which couldn't emit per-route audit metadata.\n * - Inline `if (!checkPermission('media', 'create')) ...` defenses\n * at the regenerate-variants / upload / delete branches are now\n * redundant — the wrapper enforces the permission BEFORE the\n * handler runs.\n *\n * **`matchAnyPath` rationale:** media's URL surface predates the\n * static-second-segment convention every other plugin follows\n * (`/taxonomy/<vocab>/<id>`, `/settings/<namespace>/<rest>`). The\n * second segment under `/media` is the media id itself — a runtime\n * UUID — which the dispatcher's literal `segments[0]` match would\n * miss for every request. The catch-all flag declares \"this entry\n * claims every (prefix, method) sub-path no other entry matched\" so\n * the existing URL contract works under the per-method dispatch\n * model. Static POST sub-paths (`regenerate-variants`) take\n * precedence over the catch-all entry on POST. See\n * `DefineAdminRouteSpec.matchAnyPath` in `@murumets-ee/core` for the\n * full contract.\n *\n * **Default roles:** broad for view (`['admin', 'editor', 'agent',\n * 'viewer']`), narrower for writes (`['admin', 'editor']`).\n * Conservative starting point — apps can grant more via the\n * Permissions UI.\n *\n * @example\n * ```typescript\n * import { createAdminApiHandler } from '@murumets-ee/admin-ui/server'\n * import { mediaRoutes } from '@murumets-ee/media/admin'\n * import { Media } from '@murumets-ee/media'\n *\n * const handler = createAdminApiHandler({\n * authenticate: async (req) => { ... },\n * entities: [Article, Media],\n * routes: [...mediaRoutes()],\n * })\n * ```\n */\n\nimport {\n type AdminRoute,\n type AdminRouteHandler,\n combineAdminRoutes,\n defineAdminRoute,\n safeAudit,\n} from '@murumets-ee/core'\nimport type { MediaClient } from '../client.js'\nimport type { MediaPickerItem, MediaPickerListResult } from '../picker/types.js'\n\n// ---------------------------------------------------------------------------\n// Validation\n// ---------------------------------------------------------------------------\n\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i\n\nfunction isValidUuid(value: string | undefined): value is string {\n return value !== undefined && UUID_RE.test(value)\n}\n\n/**\n * Closed enum of allowed `mediaType` filter values, in lockstep with the\n * `mediaType` field on the Media entity. The list MUST match\n * `MediaListOptions.mediaType` (declared in `../types.js`) — TypeScript\n * doesn't link the two automatically, so the small drift risk is\n * accepted in exchange for not pulling a runtime dep on the entity\n * schema package just to read its enum.\n *\n * Used as both the runtime allowlist (`isAllowedMediaType`) and the\n * source of truth for the narrowed type the guard produces — keeping\n * `as` casts off the handler's hot path.\n */\nconst ALLOWED_MEDIA_TYPES = ['image', 'video', 'audio', 'document', 'other'] as const\ntype AllowedMediaType = (typeof ALLOWED_MEDIA_TYPES)[number]\n\nfunction isAllowedMediaType(value: string): value is AllowedMediaType {\n // Cast to readonly string[] so the typed-tuple `includes` check works\n // with an arbitrary string input — `Array.prototype.includes`'s\n // signature on a typed tuple only accepts members of the tuple\n // (TS 4.9+ literal-narrowing), which is exactly what we want to\n // sidestep here.\n return (ALLOWED_MEDIA_TYPES as readonly string[]).includes(value)\n}\n\n/**\n * Hard cap on the `offset` query param. The dispatcher's allowed-pages\n * model is `limit ∈ [1, 100]`; even with the max page size that's\n * 1000 pages before hitting MAX_OFFSET, which is well beyond any\n * realistic admin-UI scroll depth. Forces slow-discard offset attacks\n * (`?offset=999999999`) to revert to a sane upper bound. Cursor-based\n * pagination would let this go higher, but the media list is\n * offset-based by convention with the entity-list shell.\n */\nconst MAX_OFFSET = 100_000\n\n/**\n * Strict non-negative integer parser for query params.\n *\n * `Number(raw)` silently coerces blanks (`'' → 0`), hex (`'0x05' → 5`),\n * exponent notation (`'1e2' → 100`), and signed (`'+5'/'-5'`) values —\n * all of which pass a downstream `Number.isInteger(n) && n >= 0` check.\n * Pre-filtering with `/^\\d+$/` keeps the contract honest: \"if you don't\n * send a pure non-negative integer string, you get the default.\" Same\n * pattern as `packages/taxonomy/src/admin/routes.ts:handleGet` tree\n * branch from PR-C-taxonomy.\n */\nfunction parseUintParam(raw: string | null, fallback: number): number {\n if (raw === null || !/^\\d+$/.test(raw)) return fallback\n const parsed = Number(raw)\n // The regex above stops hex / exponent / signed / whitespace / blank\n // inputs, but a long digit-only string still slips past — `Number(...)`\n // returns `Infinity` past ~309 digits, and precision is lost past\n // 2^53. Both would propagate through `client.findMany`'s\n // `offset: parsed` into a Postgres query that either crashes the\n // driver (`Infinity` is not a valid bigint) or silently rounds (the\n // 2^53 precision-loss boundary). Reject via `Number.isSafeInteger`\n // so overflowing inputs revert to `fallback` like every other\n // malformed value.\n if (!Number.isSafeInteger(parsed)) return fallback\n return parsed\n}\n\n// ---------------------------------------------------------------------------\n// Response helpers\n// ---------------------------------------------------------------------------\n\nfunction jsonResponse(data: unknown, status = 200): Response {\n return new Response(JSON.stringify(data), {\n status,\n headers: { 'Content-Type': 'application/json' },\n })\n}\n\nfunction jsonError(message: string, status: number): Response {\n return jsonResponse({ error: message }, status)\n}\n\n// ---------------------------------------------------------------------------\n// Per-request MediaClient factory + cached storage client\n// ---------------------------------------------------------------------------\n//\n// MediaClient and its AdminClient MUST be built per-request — AdminClient's\n// context resolver is captured eagerly at construction (see\n// buildContextResolver in @murumets-ee/core/clients). A module-level singleton\n// would bake the first request's user + tenant scope into every subsequent\n// request's writes — a cross-request permission/scope leak.\n//\n// Storage config is process-global and safe to cache once.\n\ntype StorageClient = Awaited<ReturnType<typeof import('@murumets-ee/storage').createStorageClient>>\n\ninterface StorageState {\n clientPromise: Promise<StorageClient> | null\n}\n\n// Module-level state. `null` once eviction fires on a rejection so the next\n// request gets a fresh resolution attempt (see `getStorage`'s `.catch`).\nconst storageState: StorageState = { clientPromise: null }\n\n/**\n * Resolve the process-wide storage client. The pending-promise slot is\n * cleared on rejection so a transient `createStorageClient` failure\n * (DB hiccup, misconfig) doesn't poison every subsequent media request\n * for the lifetime of the Node process. Same pattern as\n * `packages/taxonomy/src/admin/routes.ts:getClient` from PR-C-taxonomy.\n */\nasync function getStorage(): Promise<StorageClient> {\n if (!storageState.clientPromise) {\n const pending = (async () => {\n const { getApp } = await import('@murumets-ee/core')\n const { createStorageClient } = await import('@murumets-ee/storage')\n const { getStorageConfig } = await import('@murumets-ee/storage/plugin')\n const app = getApp()\n return createStorageClient(getStorageConfig(), { app })\n })()\n // Clear the slot on rejection so a transient failure doesn't poison\n // every subsequent request. `pending.catch(handler)` attaches a\n // synchronous rejection listener that resets the cached slot — the\n // handler returns `undefined`, NOT a re-throw — so the new\n // `.catch`-returned promise resolves, but we never await or hold\n // that promise. The ORIGINAL `pending` (stored in\n // `storageState.clientPromise`) is what callers `await`, and it's\n // still in its rejected state — so the caller observing this\n // resolution sees the underlying error. The `.catch` also marks\n // the rejection as \"handled\" for Node's unhandled-rejection\n // tracker. `storageState.clientPromise` holds the original `pending`\n // so concurrent in-flight callers share one resolution.\n pending.catch(() => {\n if (storageState.clientPromise === pending) storageState.clientPromise = null\n })\n storageState.clientPromise = pending\n }\n return storageState.clientPromise\n}\n\nasync function getMediaClient(): Promise<MediaClient> {\n const { createAdminClient } = await import('@murumets-ee/core/clients')\n const { MediaClient } = await import('../client.js')\n const { Media } = await import('../entity.js')\n const storage = await getStorage()\n const admin = createAdminClient(Media)\n return new MediaClient({ admin, storage })\n}\n\n// ---------------------------------------------------------------------------\n// Handlers\n// ---------------------------------------------------------------------------\n\nconst handleGet: AdminRouteHandler = async (req, ctx) => {\n const { isStorageConfigured, getStorageConfigReason } = await import('@murumets-ee/storage')\n const segments = ctx.segments\n\n // GET /media/<id>/usage — DB-only lookup, safe even when storage is\n // unconfigured. Validate the UUID first so a malformed id 400s\n // uniformly with the storage-configured branch below.\n if (segments.length === 2 && segments[1] === 'usage') {\n const id = segments[0]\n if (!isValidUuid(id)) return jsonError('Invalid media ID format', 400)\n\n const { findMediaUsages } = await import('../usage.js')\n const { getApp } = await import('@murumets-ee/core')\n const app = getApp()\n const usages = await findMediaUsages(id, app)\n return jsonResponse({ usages })\n }\n\n // Reject unknown sub-paths explicitly. The wrapper-gate has already\n // passed (caller has `media:view`); a handler-level 404 here matches\n // the dispatcher's miss-shape so unknown URLs don't fall through to\n // the single-id branch and 400/500 with a misleading reason. The\n // only valid 2-segment URL is `<id>/usage`, which was already\n // claimed by the early-return above — anything else with >=2\n // segments is not a recognized media route.\n if (segments.length >= 2) return jsonError('Not found', 404)\n\n // GET /media/<id> — validate UUID up front so a bad request still\n // 400s when storage happens to be unconfigured (matches DELETE).\n const singleId = segments.length > 0 ? segments[0] : undefined\n if (singleId !== undefined && !isValidUuid(singleId)) {\n return jsonError('Invalid media ID format', 400)\n }\n\n // Everything below needs a working storage client. If env isn't\n // wired, return a structured \"disabled\" response rather than 500 —\n // the media list page renders a banner and new admins can finish\n // onboarding without being blocked on a crash loop.\n if (!isStorageConfigured()) {\n const reason = getStorageConfigReason() ?? 'Storage not configured'\n if (segments.length > 0) {\n // Single item — treat as not-found-ish to avoid leaking\n // existence; include reason so the UI can surface it.\n return jsonResponse({ error: reason, configured: false, reason }, 503)\n }\n // GET /media — empty list + disabled flag for the picker's banner.\n const response: MediaPickerListResult & { configured: false; reason: string } = {\n items: [],\n total: 0,\n configured: false,\n reason,\n }\n return jsonResponse(response)\n }\n\n const client = await getMediaClient()\n\n // GET /media/<id> — single item with URL (full record for EntityForm + picker)\n if (singleId !== undefined) {\n const record = await client.findById(singleId)\n if (!record) return jsonError('Media not found', 404)\n\n const url = await client.getUrl(singleId)\n return jsonResponse({ ...record, url })\n }\n\n // GET /media — list with search/filter + batch URL resolution\n const url = new URL(req.url)\n const search = url.searchParams.get('search') ?? undefined\n // mediaType MUST be validated against the entity's closed enum before\n // it reaches `client.findMany` — the previous shape force-cast the raw\n // query value with `as 'image' | ...` which is a type-system lie. A\n // bogus value like `?mediaType=bogus` would parameterize into\n // `WHERE media_type = 'bogus'` (no SQL injection — Drizzle is\n // parameterized — but the row count is silently zero, which is\n // confusing). Empty string from `?mediaType=` is also passed-through\n // by the prior `?? undefined` shape since empty string is not null.\n // Allowlist + type guard drops bogus / empty values cleanly so the\n // filter is omitted instead of applied with a no-match value.\n const rawMediaType = url.searchParams.get('mediaType')\n const mediaType =\n rawMediaType !== null && isAllowedMediaType(rawMediaType) ? rawMediaType : undefined\n // Strict parsing keeps the contract honest — see `parseUintParam`\n // JSDoc. Cap limit to [1, 100] and offset to [0, MAX_OFFSET] so a\n // request can't ask for an unboundedly large page nor force a\n // slow-discard scan with `?offset=99999999`.\n const limit = Math.min(Math.max(parseUintParam(url.searchParams.get('limit'), 24), 1), 100)\n const offset = Math.min(parseUintParam(url.searchParams.get('offset'), 0), MAX_OFFSET)\n\n const result = await client.findMany({\n ...(search !== undefined && { search }),\n ...(mediaType !== undefined && { mediaType }),\n limit,\n offset,\n })\n\n // Resolve original URLs + thumbnail variant URLs for all items.\n const ids = result.items.map((item) => item.id)\n const [urlMap, thumbMap] = await Promise.all([\n client.getUrls(ids),\n client.getVariantUrls(ids, 'thumbnail'),\n ])\n\n const items: (MediaPickerItem & { thumbnailUrl?: string })[] = result.items.map((item) => {\n const thumbnailUrl = thumbMap.get(item.id)\n return {\n id: item.id,\n title: item.title ?? null,\n alt: item.alt ?? null,\n filename: item.filename,\n mimeType: item.mimeType,\n size: item.size,\n mediaType: item.mediaType,\n url: urlMap.get(item.id) ?? '',\n ...(thumbnailUrl !== undefined && { thumbnailUrl }),\n width: item.width ?? null,\n height: item.height ?? null,\n }\n })\n\n const response: MediaPickerListResult = { items, total: result.total }\n return jsonResponse(response)\n}\n\nconst handleUpload: AdminRouteHandler = async (req, ctx) => {\n const { isStorageConfigured, getStorageConfigReason, detectMimeType } = await import(\n '@murumets-ee/storage'\n )\n\n // Upload is registered at `path: ''` (NOT matchAnyPath) — the\n // dispatcher only invokes this handler when segments=[]. The api-\n // handler ALSO rejects empty/whitespace-only first segments with a\n // 400 before any plugin dispatcher runs (see\n // `packages/admin-ui/src/server/api-handler/index.ts` segment-\n // validation block). So this guard is defense-in-depth — per HANDOFF\n // §\"Defense-in-depth `&& segments[i]` guards are fine\" — protecting\n // against a future framework invariant change that lets a non-empty\n // segment reach a `path: ''` static entry.\n if (ctx.segments.length > 0) return jsonError('Not found', 404)\n\n if (!isStorageConfigured()) {\n return jsonError(getStorageConfigReason() ?? 'Storage not configured', 503)\n }\n\n const client = await getMediaClient()\n\n const formData = await req.formData()\n const file = formData.get('file')\n // FormData `get` returns string | File | null. Reject anything that\n // isn't a File so the typed `file.size`/`file.arrayBuffer()` below\n // is safe without a runtime cast.\n if (!(file instanceof File) || file.size === 0) {\n return jsonError('No file provided', 400)\n }\n\n // Guard against oversized uploads (50 MB limit). Hardcoded rather\n // than read from getMediaConfig() to keep this handler independent\n // of plugin-init order — the plugin's resolved config may not be\n // populated yet under CLI / non-RSC startup paths.\n const MAX_UPLOAD_SIZE = 50 * 1024 * 1024\n if (file.size > MAX_UPLOAD_SIZE) {\n return jsonError(\n `File too large: ${(file.size / 1024 / 1024).toFixed(1)} MB exceeds 50 MB limit`,\n 400,\n )\n }\n\n const buffer = Buffer.from(await file.arrayBuffer())\n\n // Detect actual MIME type from file content (prevents spoofing).\n const { mimeType, mismatch } = await detectMimeType(\n buffer,\n file.type || 'application/octet-stream',\n )\n if (mismatch) {\n return jsonError(\n `File content doesn't match declared type: claimed ${file.type}, detected ${mimeType}`,\n 400,\n )\n }\n\n const result = await client.upload(buffer, {\n filename: file.name,\n mimeType,\n size: file.size,\n uploadedBy: ctx.user.id,\n })\n\n const item: MediaPickerItem = {\n id: result.media.id,\n title: result.media.title ?? null,\n alt: result.media.alt ?? null,\n filename: result.media.filename,\n mimeType: result.media.mimeType,\n size: result.media.size,\n mediaType: result.media.mediaType,\n url: result.url,\n width: result.media.width ?? null,\n height: result.media.height ?? null,\n }\n\n safeAudit(ctx, {\n action: 'media.upload',\n entityType: 'media',\n entityId: result.media.id,\n userId: ctx.user.id,\n ...(ctx.user.name !== undefined && { userName: ctx.user.name }),\n changes: {\n filename: result.media.filename,\n mimeType: result.media.mimeType,\n size: result.media.size,\n mediaType: result.media.mediaType,\n },\n })\n\n return jsonResponse(item, 201)\n}\n\nconst handleRegenerateVariants: AdminRouteHandler = async (_req, ctx) => {\n const { isStorageConfigured, getStorageConfigReason } = await import('@murumets-ee/storage')\n\n // Static POST path='regenerate-variants' — the dispatcher only invokes\n // this handler when `segments[0] === 'regenerate-variants'`. Trailing\n // segments (e.g. POST /media/regenerate-variants/extra) aren't a\n // supported sub-route.\n if (ctx.segments.length !== 1) return jsonError('Not found', 404)\n\n if (!isStorageConfigured()) {\n return jsonError(getStorageConfigReason() ?? 'Storage not configured', 503)\n }\n\n const { regenerateAllVariants } = await import('../regenerate-variants.js')\n const { getApp, getContext } = await import('@murumets-ee/core')\n const { resolveImageStyles } = await import('../resolve-image-styles.js')\n const { createStorageClient } = await import('@murumets-ee/storage')\n const { getStorageConfig } = await import('@murumets-ee/storage/plugin')\n\n const app = getApp()\n const styles = await resolveImageStyles(app, app.logger)\n if (!styles || Object.keys(styles).length === 0) {\n return jsonError('No image styles configured', 400)\n }\n\n const storageConfig = getStorageConfig()\n const storage = createStorageClient(storageConfig, { app })\n\n const result = await regenerateAllVariants({\n app,\n storage,\n logger: app.logger.child({ media: true }),\n styles,\n contextResolver: () => {\n const requestCtx = getContext()\n if (!requestCtx?.user || !requestCtx?.checker) return undefined\n return {\n user: requestCtx.user,\n checker: requestCtx.checker,\n ...(requestCtx.scope !== undefined && { scope: requestCtx.scope }),\n }\n },\n })\n\n safeAudit(ctx, {\n action: 'media.regenerate_variants',\n userId: ctx.user.id,\n ...(ctx.user.name !== undefined && { userName: ctx.user.name }),\n metadata: { total: result.total, processed: result.processed, errors: result.errors },\n })\n\n return jsonResponse(result)\n}\n\nconst handleDelete: AdminRouteHandler = async (_req, ctx) => {\n const segments = ctx.segments\n\n // DELETE /media — no id supplied. Reject as 400, NOT 404, so a\n // caller confusing \"no id\" with \"id not found\" gets a meaningful\n // error. The wrapper-gate has already validated the caller has\n // media:delete, so the 400 isn't an information-disclosure vector.\n if (segments.length === 0) return jsonError('Media ID required', 400)\n\n // Reject sub-paths beyond /<id> — DELETE /media/<id>/usage etc.\n if (segments.length > 1) return jsonError('Not found', 404)\n\n const id = segments[0]\n if (!isValidUuid(id)) return jsonError('Invalid media ID format', 400)\n\n const { isStorageConfigured, getStorageConfigReason } = await import('@murumets-ee/storage')\n if (!isStorageConfigured()) {\n // Can't safely delete — MediaClient needs storage to remove the\n // actual object, and partial delete (DB row gone, object orphaned)\n // would leak storage. Surface the reason so the UI can display it.\n return jsonError(getStorageConfigReason() ?? 'Storage not configured', 503)\n }\n\n // AdminClient.delete() checks entity_refs and throws\n // ReferencedEntityError if this media is still referenced. The\n // error bubbles to the caller's error handler which returns 409\n // with usage details.\n const client = await getMediaClient()\n await client.delete(id)\n\n safeAudit(ctx, {\n action: 'media.delete',\n entityType: 'media',\n entityId: id,\n userId: ctx.user.id,\n ...(ctx.user.name !== undefined && { userName: ctx.user.name }),\n })\n\n return jsonResponse({ deleted: 1 })\n}\n\n// ---------------------------------------------------------------------------\n// Route factory\n// ---------------------------------------------------------------------------\n\n/**\n * Default roles for view: broad reach across the admin shell.\n *\n * `BUILT_IN_ROLES` in `packages/auth/src/permissions.ts` is exactly\n * `['admin', 'public', 'authenticated', 'agent']` — `admin` is\n * hardcoded as an unconditional yes in `buildPermissionChecker`,\n * `agent` is the only non-admin built-in that flows through\n * `buildInitialRoleDefinitions()` + `upsertBuiltInRoles`. The\n * `agent` entry in this list is what gives ops agents read-only\n * media access on first boot of a fresh install.\n *\n * `editor` and `viewer` are CONVENTIONAL app-defined roles —\n * apps that follow the scaffold pattern create them as part of\n * their own role catalog. Including them in `defaultRoles` doesn't\n * seed them (the seeder only iterates the built-ins above), but\n * the values DO flow into the process-local permission catalog\n * (see `registerPermission` in `@murumets-ee/core`), which the\n * forthcoming Permission Matrix UI (PR-D) reads to show \"this\n * route's recommended default grants\" against the app's actual\n * role set. The catalog is also the mechanism via which a future\n * upgrade of `upsertBuiltInRoles` could extend the seed surface\n * to app-defined roles without each plugin having to re-declare\n * its defaults.\n */\nconst VIEW_DEFAULT_ROLES = ['admin', 'editor', 'agent', 'viewer'] as const\n\n/** Default roles for create/delete — narrower than view. */\nconst WRITE_DEFAULT_ROLES = ['admin', 'editor'] as const\n\n/**\n * Build admin API routes for media management.\n *\n * Returns `AdminRoute[]` from `combineAdminRoutes` — one entry per\n * `(prefix, method)` after grouping. Callers spread the result into\n * their top-level routes list: `routes: [...mediaRoutes()]`.\n *\n * Four `defineAdminRoute` entries:\n *\n * - GET matchAnyPath with `media:view` defaultRoles: VIEW_DEFAULT_ROLES\n * - POST path='' `media:create` defaultRoles: WRITE_DEFAULT_ROLES\n * - POST path='regenerate-variants' `media:create` defaultRoles: WRITE_DEFAULT_ROLES\n * - DELETE matchAnyPath with `media:delete` defaultRoles: WRITE_DEFAULT_ROLES\n *\n * Permissions are auto-registered by the entity catalog\n * (`buildResourceCatalog` in `@murumets-ee/auth`) AND by\n * `registerPermission` inside `defineAdminRoute`. Idempotent —\n * `registerPermission` unions `defaultRoles` on repeat registration,\n * so the framework's two pathways agree on the final grant set.\n *\n * Standard entity CRUD (PATCH with translations) is NOT registered\n * here — it falls through to the generic entity handler. Add `Media`\n * to the `entities` array in your handler config to enable it.\n */\nexport function mediaRoutes(): AdminRoute[] {\n const entries = [\n defineAdminRoute({\n prefix: 'media',\n path: '',\n method: 'GET',\n permission: 'media:view',\n defaultRoles: VIEW_DEFAULT_ROLES,\n matchAnyPath: true,\n description: 'Read media — list, single item, or referencing-entity usage report.',\n handler: handleGet,\n }),\n defineAdminRoute({\n prefix: 'media',\n path: '',\n method: 'POST',\n permission: 'media:create',\n defaultRoles: WRITE_DEFAULT_ROLES,\n description: 'Upload a media file (multipart FormData with `file` field).',\n handler: handleUpload,\n }),\n defineAdminRoute({\n prefix: 'media',\n path: 'regenerate-variants',\n method: 'POST',\n permission: 'media:create',\n defaultRoles: WRITE_DEFAULT_ROLES,\n description: 'Regenerate every image-style variant for every media row.',\n handler: handleRegenerateVariants,\n }),\n defineAdminRoute({\n prefix: 'media',\n path: '',\n method: 'DELETE',\n permission: 'media:delete',\n defaultRoles: WRITE_DEFAULT_ROLES,\n matchAnyPath: true,\n description: 'Delete a media record + its storage object.',\n handler: handleDelete,\n }),\n ]\n\n return combineAdminRoutes(entries)\n}\n"],"mappings":"4FA0EA,MAAM,EAAU,kEAEhB,SAAS,EAAY,EAA4C,CAC/D,OAAO,IAAU,IAAA,IAAa,EAAQ,KAAK,EAAM,CAenD,MAAM,EAAsB,CAAC,QAAS,QAAS,QAAS,WAAY,QAAQ,CAG5E,SAAS,EAAmB,EAA0C,CAMpE,OAAQ,EAA0C,SAAS,EAAM,CAyBnE,SAAS,EAAe,EAAoB,EAA0B,CACpE,GAAI,IAAQ,MAAQ,CAAC,QAAQ,KAAK,EAAI,CAAE,OAAO,EAC/C,IAAM,EAAS,OAAO,EAAI,CAW1B,OADK,OAAO,cAAc,EAAO,CAC1B,EADmC,EAQ5C,SAAS,EAAa,EAAe,EAAS,IAAe,CAC3D,OAAO,IAAI,SAAS,KAAK,UAAU,EAAK,CAAE,CACxC,SACA,QAAS,CAAE,eAAgB,mBAAoB,CAChD,CAAC,CAGJ,SAAS,EAAU,EAAiB,EAA0B,CAC5D,OAAO,EAAa,CAAE,MAAO,EAAS,CAAE,EAAO,CAuBjD,MAAM,EAA6B,CAAE,cAAe,KAAM,CAS1D,eAAe,GAAqC,CAClD,GAAI,CAAC,EAAa,cAAe,CAC/B,IAAM,GAAW,SAAY,CAC3B,GAAM,CAAE,UAAW,MAAM,OAAO,qBAC1B,CAAE,uBAAwB,MAAM,OAAO,wBACvC,CAAE,oBAAqB,MAAM,OAAO,+B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AAQ,QACR,KAAM,GACN,OAAQ,SACR,WAAY,eACZ,aAAc,EACd,aAAc,GACd,YAAa,8CACb,QAAS,EACV,CAAC,CAG6B,CAAC"}
@@ -1,4 +1,3 @@
1
- import * as _$_murumets_ee_entity0 from "@murumets-ee/entity";
2
1
  import { InferEntityDTO } from "@murumets-ee/entity";
3
2
  import { FileVisibility } from "@murumets-ee/storage";
4
3
 
@@ -19,47 +18,47 @@ import { FileVisibility } from "@murumets-ee/storage";
19
18
  * })
20
19
  * ```
21
20
  */
22
- declare const Media: _$_murumets_ee_entity0.Entity<{
23
- id: _$_murumets_ee_entity0.IdField;
24
- } & _$_murumets_ee_entity0.AuditableFields & {
25
- title: _$_murumets_ee_entity0.TextField & {
21
+ declare const Media: import("@murumets-ee/entity").Entity<{
22
+ id: import("@murumets-ee/entity").IdField;
23
+ } & import("@murumets-ee/entity").AuditableFields & {
24
+ title: import("@murumets-ee/entity").TextField & {
26
25
  readonly translatable: true;
27
26
  };
28
- alt: _$_murumets_ee_entity0.TextField & {
27
+ alt: import("@murumets-ee/entity").TextField & {
29
28
  readonly translatable: true;
30
29
  };
31
- description: _$_murumets_ee_entity0.TextField & {
30
+ description: import("@murumets-ee/entity").TextField & {
32
31
  readonly translatable: true;
33
32
  }; /** Key into toolkit_files table (e.g., 'uploads/2026/02/uuid/photo.jpg') */
34
- fileKey: _$_murumets_ee_entity0.TextField & {
33
+ fileKey: import("@murumets-ee/entity").TextField & {
35
34
  readonly required: true;
36
35
  readonly indexed: true;
37
36
  };
38
- filename: _$_murumets_ee_entity0.TextField & {
37
+ filename: import("@murumets-ee/entity").TextField & {
39
38
  readonly required: true;
40
39
  };
41
- mimeType: _$_murumets_ee_entity0.TextField & {
40
+ mimeType: import("@murumets-ee/entity").TextField & {
42
41
  readonly required: true;
43
42
  readonly indexed: true;
44
43
  };
45
- size: _$_murumets_ee_entity0.NumberField & {
44
+ size: import("@murumets-ee/entity").NumberField & {
46
45
  readonly required: true;
47
46
  readonly integer: true;
48
47
  };
49
- width: _$_murumets_ee_entity0.NumberField & {
48
+ width: import("@murumets-ee/entity").NumberField & {
50
49
  readonly integer: true;
51
50
  };
52
- height: _$_murumets_ee_entity0.NumberField & {
51
+ height: import("@murumets-ee/entity").NumberField & {
53
52
  readonly integer: true;
54
53
  };
55
- mediaType: _$_murumets_ee_entity0.SelectField & {
54
+ mediaType: import("@murumets-ee/entity").SelectField & {
56
55
  options: readonly ["image", "video", "audio", "document", "other"];
57
56
  } & {
58
57
  readonly options: readonly ["image", "video", "audio", "document", "other"];
59
58
  readonly required: true;
60
59
  readonly indexed: true;
61
60
  };
62
- }>;
61
+ }, "media", [import("@murumets-ee/entity").Behavior<import("@murumets-ee/entity").AuditableFields, string>, import("@murumets-ee/entity").SearchableBehavior]>;
63
62
  //#endregion
64
63
  //#region src/types.d.ts
65
64
  /** Media type derived from MIME type */
@@ -152,4 +151,4 @@ interface MediaPluginConfig {
152
151
  }
153
152
  //#endregion
154
153
  export { MediaRecord as a, MediaUploadResult as c, MediaPluginConfig as i, Media as l, MediaListOptions as n, MediaType as o, MediaListResult as r, MediaUploadOptions as s, ImageStyle as t };
155
- //# sourceMappingURL=types-BMW3aeEB.d.mts.map
154
+ //# sourceMappingURL=types-CqjShq2U.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types-CqjShq2U.d.mts","names":[],"sources":["../src/entity.ts","../src/types.ts"],"mappings":";;;;;;;;AAmBA;;;;;;;;;;;;cAAa,KAAA,gCAAK,MAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KCdN,SAAA;;UAGK,kBAAA;EDgEf;EC9DA,QAAA;;EAEA,QAAA;;EAEA,IAAA;;EAEA,UAAA,GAAa,cAAA;;EAEb,KAAA;;EAEA,GAAA;;EAEA,WAAA;;EAEA,KAAA;;EAEA,MAAA;;EAEA,UAAA;AAAA;;UAIe,iBAAA;;EAEf,KAAA,EAAO,WAAA;;EAEP,GAAA;AAAA;;;;;;;;KAUU,WAAA,GAAc,cAAA,QAAsB,KAAA,CAAM,SAAA;;UAGrC,gBAAA;;EAEf,SAAA,GAAY,SAAA;;EAEZ,cAAA;;EAEA,MAAA;;EAEA,KAAA;;EAEA,MAAA;;EAEA,OAAA;EAxDmB;EA0DnB,cAAA;AAAA;;UAIe,eAAA;EACf,KAAA,EAAO,WAAA;EACP,KAAA;EACA,KAAA;EACA,MAAA;AAAA;;UAIe,UAAA;EA3DF;EA6Db,KAAA;EAzDA;EA2DA,MAAA;EAvDA;EAyDA,GAAA;EArDA;EAuDA,MAAA;EAvDU;EAyDV,OAAA;AAAA;;UAIe,iBAAA;EAvDf;EAyDA,aAAA;EAvDA;EAyDA,aAAA;EAzDG;EA2DH,iBAAA,GAAoB,cAAA;EAjDC;EAmDrB,WAAA,GAAc,MAAA,SAAe,UAAA;AAAA"}
@@ -0,0 +1,2 @@
1
+ import"server-only";import{findEntityUsages as e}from"@murumets-ee/entity/refs";async function t(t,n){return(await e(`media`,t,n.db.readOnly)).map(e=>{let t=`field`,r=n.entities.get(e.sourceEntity);if(r){let n=r.allFields[e.sourceField];n&&n.type===`blocks`&&(t=`block`)}return{entityName:e.sourceEntity,entityId:e.sourceId,fieldName:e.sourceField,context:t}})}export{t as findMediaUsages};
2
+ //# sourceMappingURL=usage-BwUdYWkA.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"usage-BwUdYWkA.mjs","names":[],"sources":["../src/usage.ts"],"sourcesContent":["/**\n * Media usage lookup — finds all entity references to a media item.\n *\n * Delegates to the universal entity_refs tracking table (populated at write time\n * by AdminClient). One indexed query instead of scanning every table.\n *\n * Used by delete protection (409 Conflict) and the usage API endpoint.\n */\n\nimport 'server-only'\n\nimport type { ToolkitApp } from '@murumets-ee/core'\nimport { findEntityUsages } from '@murumets-ee/entity/refs'\n\nexport interface MediaUsage {\n entityName: string\n entityId: string\n fieldName: string\n /** 'field' = entity column, 'block' = layout/blocks field */\n context: 'field' | 'block'\n}\n\n/**\n * Find all entities that reference a given media ID.\n *\n * @param mediaId - UUID of the media item to check\n * @param app - Toolkit app (provides db + entity registry)\n * @returns Array of usage records (empty if unreferenced)\n */\nexport async function findMediaUsages(\n mediaId: string,\n app: ToolkitApp,\n): Promise<MediaUsage[]> {\n const usages = await findEntityUsages('media', mediaId, app.db.readOnly)\n\n // Derive context from field name — blocks fields are tracked with their field name\n // which we can check against entity definitions. For simplicity, we check if the\n // source entity has a blocks-type field matching the source field name.\n return usages.map((usage) => {\n let context: 'field' | 'block' = 'field'\n const entity = app.entities.get(usage.sourceEntity)\n if (entity) {\n const fieldConfig = entity.allFields[usage.sourceField]\n if (fieldConfig && fieldConfig.type === 'blocks') {\n context = 'block'\n }\n }\n\n return {\n entityName: usage.sourceEntity,\n entityId: usage.sourceId,\n fieldName: usage.sourceField,\n context,\n }\n })\n}\n"],"mappings":"gFA6BA,eAAsB,EACpB,EACA,EACuB,CAMvB,OAAO,MALc,EAAiB,QAAS,EAAS,EAAI,GAAG,SAAS,EAK1D,IAAK,GAAU,CAC3B,IAAI,EAA6B,QAC3B,EAAS,EAAI,SAAS,IAAI,EAAM,aAAa,CACnD,GAAI,EAAQ,CACV,IAAM,EAAc,EAAO,UAAU,EAAM,aACvC,GAAe,EAAY,OAAS,WACtC,EAAU,SAId,MAAO,CACL,WAAY,EAAM,aAClB,SAAU,EAAM,SAChB,UAAW,EAAM,YACjB,UACD,EACD"}
package/dist/usage.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { PostgresJsDatabase } from "drizzle-orm/postgres-js";
1
+ import { ToolkitApp } from "@murumets-ee/core";
2
2
 
3
3
  //#region src/usage.d.ts
4
4
  interface MediaUsage {
@@ -12,10 +12,10 @@ interface MediaUsage {
12
12
  * Find all entities that reference a given media ID.
13
13
  *
14
14
  * @param mediaId - UUID of the media item to check
15
- * @param db - Database connection
15
+ * @param app - Toolkit app (provides db + entity registry)
16
16
  * @returns Array of usage records (empty if unreferenced)
17
17
  */
18
- declare function findMediaUsages(mediaId: string, db: PostgresJsDatabase): Promise<MediaUsage[]>;
18
+ declare function findMediaUsages(mediaId: string, app: ToolkitApp): Promise<MediaUsage[]>;
19
19
  //#endregion
20
20
  export { MediaUsage, findMediaUsages };
21
21
  //# sourceMappingURL=usage.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"usage.d.mts","names":[],"sources":["../src/usage.ts"],"mappings":";;;UAciB,UAAA;EACf,UAAA;EACA,QAAA;EACA,SAAA;EAYoB;EAVpB,OAAA;AAAA;;;;;;;;iBAUoB,eAAA,CACpB,OAAA,UACA,EAAA,EAAI,kBAAA,GACH,OAAA,CAAQ,UAAA"}
1
+ {"version":3,"file":"usage.d.mts","names":[],"sources":["../src/usage.ts"],"mappings":";;;UAciB,UAAA;EACf,UAAA;EACA,QAAA;EACA,SAAA;EAYoB;EAVpB,OAAA;AAAA;;;;;;;;iBAUoB,eAAA,CACpB,OAAA,UACA,GAAA,EAAK,UAAA,GACJ,OAAA,CAAQ,UAAA"}
package/dist/usage.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import"server-only";import{findEntityUsages as e}from"@murumets-ee/entity/refs";async function t(t,n){let r=await e(`media`,t,n),{getApp:i}=await import(`@murumets-ee/core`),a=i();return r.map(e=>{let t=`field`,n=a.entities.get(e.sourceEntity);if(n){let r=n.allFields[e.sourceField];r&&r.type===`blocks`&&(t=`block`)}return{entityName:e.sourceEntity,entityId:e.sourceId,fieldName:e.sourceField,context:t}})}export{t as findMediaUsages};
1
+ import"server-only";import{findEntityUsages as e}from"@murumets-ee/entity/refs";async function t(t,n){return(await e(`media`,t,n.db.readOnly)).map(e=>{let t=`field`,r=n.entities.get(e.sourceEntity);if(r){let n=r.allFields[e.sourceField];n&&n.type===`blocks`&&(t=`block`)}return{entityName:e.sourceEntity,entityId:e.sourceId,fieldName:e.sourceField,context:t}})}export{t as findMediaUsages};
2
2
  //# sourceMappingURL=usage.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"usage.mjs","names":[],"sources":["../src/usage.ts"],"sourcesContent":["/**\n * Media usage lookup — finds all entity references to a media item.\n *\n * Delegates to the universal entity_refs tracking table (populated at write time\n * by AdminClient). One indexed query instead of scanning every table.\n *\n * Used by delete protection (409 Conflict) and the usage API endpoint.\n */\n\nimport 'server-only'\n\nimport { findEntityUsages } from '@murumets-ee/entity/refs'\nimport type { PostgresJsDatabase } from 'drizzle-orm/postgres-js'\n\nexport interface MediaUsage {\n entityName: string\n entityId: string\n fieldName: string\n /** 'field' = entity column, 'block' = layout/blocks field */\n context: 'field' | 'block'\n}\n\n/**\n * Find all entities that reference a given media ID.\n *\n * @param mediaId - UUID of the media item to check\n * @param db - Database connection\n * @returns Array of usage records (empty if unreferenced)\n */\nexport async function findMediaUsages(\n mediaId: string,\n db: PostgresJsDatabase,\n): Promise<MediaUsage[]> {\n const usages = await findEntityUsages('media', mediaId, db)\n\n // Derive context from field name — blocks fields are tracked with their field name\n // which we can check against entity definitions. For simplicity, we check if the\n // source entity has a blocks-type field matching the source field name.\n const { getApp } = await import('@murumets-ee/core')\n const app = getApp()\n\n return usages.map((usage) => {\n let context: 'field' | 'block' = 'field'\n const entity = app.entities.get(usage.sourceEntity)\n if (entity) {\n const fieldConfig = entity.allFields[usage.sourceField]\n if (fieldConfig && fieldConfig.type === 'blocks') {\n context = 'block'\n }\n }\n\n return {\n entityName: usage.sourceEntity,\n entityId: usage.sourceId,\n fieldName: usage.sourceField,\n context,\n }\n })\n}\n"],"mappings":"gFA6BA,eAAsB,EACpB,EACA,EACuB,CACvB,IAAM,EAAS,MAAM,EAAiB,QAAS,EAAS,EAAG,CAKrD,CAAE,UAAW,MAAM,OAAO,qBAC1B,EAAM,GAAQ,CAEpB,OAAO,EAAO,IAAK,GAAU,CAC3B,IAAI,EAA6B,QAC3B,EAAS,EAAI,SAAS,IAAI,EAAM,aAAa,CACnD,GAAI,EAAQ,CACV,IAAM,EAAc,EAAO,UAAU,EAAM,aACvC,GAAe,EAAY,OAAS,WACtC,EAAU,SAId,MAAO,CACL,WAAY,EAAM,aAClB,SAAU,EAAM,SAChB,UAAW,EAAM,YACjB,UACD,EACD"}
1
+ {"version":3,"file":"usage.mjs","names":[],"sources":["../src/usage.ts"],"sourcesContent":["/**\n * Media usage lookup — finds all entity references to a media item.\n *\n * Delegates to the universal entity_refs tracking table (populated at write time\n * by AdminClient). One indexed query instead of scanning every table.\n *\n * Used by delete protection (409 Conflict) and the usage API endpoint.\n */\n\nimport 'server-only'\n\nimport type { ToolkitApp } from '@murumets-ee/core'\nimport { findEntityUsages } from '@murumets-ee/entity/refs'\n\nexport interface MediaUsage {\n entityName: string\n entityId: string\n fieldName: string\n /** 'field' = entity column, 'block' = layout/blocks field */\n context: 'field' | 'block'\n}\n\n/**\n * Find all entities that reference a given media ID.\n *\n * @param mediaId - UUID of the media item to check\n * @param app - Toolkit app (provides db + entity registry)\n * @returns Array of usage records (empty if unreferenced)\n */\nexport async function findMediaUsages(\n mediaId: string,\n app: ToolkitApp,\n): Promise<MediaUsage[]> {\n const usages = await findEntityUsages('media', mediaId, app.db.readOnly)\n\n // Derive context from field name — blocks fields are tracked with their field name\n // which we can check against entity definitions. For simplicity, we check if the\n // source entity has a blocks-type field matching the source field name.\n return usages.map((usage) => {\n let context: 'field' | 'block' = 'field'\n const entity = app.entities.get(usage.sourceEntity)\n if (entity) {\n const fieldConfig = entity.allFields[usage.sourceField]\n if (fieldConfig && fieldConfig.type === 'blocks') {\n context = 'block'\n }\n }\n\n return {\n entityName: usage.sourceEntity,\n entityId: usage.sourceId,\n fieldName: usage.sourceField,\n context,\n }\n })\n}\n"],"mappings":"gFA6BA,eAAsB,EACpB,EACA,EACuB,CAMvB,OAAO,MALc,EAAiB,QAAS,EAAS,EAAI,GAAG,SAAS,EAK1D,IAAK,GAAU,CAC3B,IAAI,EAA6B,QAC3B,EAAS,EAAI,SAAS,IAAI,EAAM,aAAa,CACnD,GAAI,EAAQ,CACV,IAAM,EAAc,EAAO,UAAU,EAAM,aACvC,GAAe,EAAY,OAAS,WACtC,EAAU,SAId,MAAO,CACL,WAAY,EAAM,aAClB,SAAU,EAAM,SAChB,UAAW,EAAM,YACjB,UACD,EACD"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@murumets-ee/media",
3
- "version": "0.19.0",
3
+ "version": "0.20.0",
4
4
  "license": "Elastic-2.0",
5
5
  "type": "module",
6
6
  "exports": {
@@ -57,13 +57,13 @@
57
57
  "sharp": "^0.34.5",
58
58
  "tailwind-merge": "^2.6.0",
59
59
  "zod": "^3.24.1",
60
- "@murumets-ee/core": "0.19.0",
61
- "@murumets-ee/entity": "0.19.0",
62
- "@murumets-ee/db": "0.19.0",
63
- "@murumets-ee/logging": "0.19.0",
64
- "@murumets-ee/settings": "0.19.0",
65
- "@murumets-ee/storage": "0.19.0",
66
- "@murumets-ee/ui": "0.19.0"
60
+ "@murumets-ee/core": "0.20.0",
61
+ "@murumets-ee/db": "0.20.0",
62
+ "@murumets-ee/entity": "0.20.0",
63
+ "@murumets-ee/logging": "0.20.0",
64
+ "@murumets-ee/settings": "0.20.0",
65
+ "@murumets-ee/storage": "0.20.0",
66
+ "@murumets-ee/ui": "0.20.0"
67
67
  },
68
68
  "peerDependencies": {
69
69
  "lucide-react": ">=0.400.0",
@@ -88,6 +88,7 @@
88
88
  "scripts": {
89
89
  "build": "tsdown",
90
90
  "dev": "tsdown --watch",
91
- "test": "vitest"
91
+ "test": "vitest run",
92
+ "test:watch": "vitest"
92
93
  }
93
94
  }
@@ -1,2 +0,0 @@
1
- import"./routes-BFRoQhZB.mjs";import"./entity-B75A4L3p.mjs";import"./image-styles-settings-B4QOt7Ve.mjs";import"@murumets-ee/media/image-styles";function e(){throw Error(`@murumets-ee/media plugin not initialized. Add media() to your plugins array.`)}export{e as getMediaConfig};
2
- //# sourceMappingURL=plugin-DZaF1BHS.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"plugin-DZaF1BHS.mjs","names":[],"sources":["../src/plugin.ts"],"sourcesContent":["/**\n * Media plugin — auto-registers the Media entity, mounts admin routes, and\n * contributes sidebar + default-route scaffolding for the admin shell.\n *\n * @example\n * ```typescript\n * import { media } from '@murumets-ee/media/plugin'\n *\n * export default defineLumiConfig({\n * plugins: [\n * storage(),\n * media({ maxUploadSize: 10 * 1024 * 1024 }),\n * ],\n * })\n * ```\n */\n\nimport type { Plugin, PluginSettingsDefinition } from '@murumets-ee/core'\n// Self-reference the `./image-styles` subpath (not the internal source\n// files) so the plugin bundle externalizes the React components instead\n// of inlining them — the subpath is built separately with a `'use client'`\n// banner, and Next.js needs to see that boundary preserved.\nimport { ImageStylesManager, RegenerateVariantsAction } from '@murumets-ee/media/image-styles'\nimport { mediaRoutes } from './admin/routes.js'\nimport { Media } from './entity.js'\nimport { imageStylesSettings } from './image-styles-settings.js'\nimport type { MediaPluginConfig } from './types.js'\n\nlet _mediaConfig: Required<MediaPluginConfig> | null = null\n\n/**\n * Get the resolved media plugin configuration.\n * Throws if plugin not initialized.\n */\nexport function getMediaConfig(): Required<MediaPluginConfig> {\n if (!_mediaConfig) {\n throw new Error('@murumets-ee/media plugin not initialized. Add media() to your plugins array.')\n }\n return _mediaConfig\n}\n\n/**\n * Media plugin factory.\n *\n * - Registers the Media entity\n * - Mounts the media admin API routes\n * - Contributes sidebar + default-route metadata\n * - Validates that @murumets-ee/storage + @murumets-ee/settings are registered at init\n * - Captures resolved configuration for `getMediaConfig()`\n */\nexport function media(config?: MediaPluginConfig): Plugin {\n const resolvedConfig: Required<MediaPluginConfig> = {\n acceptedTypes: config?.acceptedTypes ?? ['image/*', 'video/*', 'audio/*', 'application/pdf'],\n maxUploadSize: config?.maxUploadSize ?? 50 * 1024 * 1024,\n defaultVisibility: config?.defaultVisibility ?? 'public',\n imageStyles: config?.imageStyles ?? {\n thumbnail: { width: 200, height: 200, fit: 'cover', format: 'webp', quality: 80 },\n },\n }\n\n return {\n name: '@murumets-ee/media',\n shared: {\n // Self-contributes the media.imageStyles namespace. The merge engine\n // auto-derives the permission resource (`settings:media.imageStyles`)\n // and the sidebar entry under \"Settings\" group; the settings plugin's\n // init hook picks it up for route dispatch. Apps don't have to wire\n // anything — adding `media()` to plugins is enough.\n settings: [imageStylesSettings as PluginSettingsDefinition],\n },\n server: {\n entities: [Media],\n routes: [mediaRoutes()],\n init: async (app) => {\n if (!app.plugins.has('@murumets-ee/storage')) {\n throw new Error(\n '@murumets-ee/media requires @murumets-ee/storage plugin. ' +\n 'Add storage() before media() in your plugins array.',\n )\n }\n\n if (!app.plugins.has('@murumets-ee/settings')) {\n throw new Error(\n '@murumets-ee/media requires @murumets-ee/settings plugin. ' +\n 'Add settings() before media() in your plugins array.',\n )\n }\n\n _mediaConfig = resolvedConfig\n\n // Image style defaults live in the plugin config and are exposed via\n // `getMediaConfig()`. Persistent overrides go to the settings DB\n // through the generic settings API at `/api/admin/settings/media.imageStyles`\n // — see `image-styles-settings.ts`. `resolveImageStyles` reads\n // DB-first, config-fallback.\n //\n // We deliberately do NOT seed the DB here. Init must stay lightweight:\n // it runs in every context (Next.js server, Next.js build, CLI commands).\n // The prior eager-seed path pulled in `@murumets-ee/settings`'s main entry —\n // which carries `import 'server-only'` — and crashed non-RSC Node bootstrap.\n\n app.logger.info(\n {\n acceptedTypes: resolvedConfig.acceptedTypes,\n maxUploadSize: resolvedConfig.maxUploadSize,\n defaultVisibility: resolvedConfig.defaultVisibility,\n },\n 'Media plugin initialized',\n )\n },\n },\n adminUi: {\n sidebar: [\n {\n id: 'media',\n group: 'Library',\n label: 'Media',\n href: '/admin/media',\n iconName: 'image',\n },\n ],\n defaultRoutes: [\n {\n path: 'media',\n factory: 'MediaListPage',\n nav: { label: 'Media', iconName: 'image', group: 'Library' },\n },\n {\n path: 'media/[id]',\n factory: 'MediaEditPage',\n },\n ],\n // Self-contributes the rich image-styles editor and the\n // \"Regenerate All Variants\" action. Apps don't have to wire either\n // — they appear automatically on /admin/settings/media.imageStyles\n // (route + sidebar entry auto-derived from `shared.settings`).\n settingRenderers: {\n 'media.imageStyles': ImageStylesManager,\n },\n settingsActions: {\n 'media.imageStyles': RegenerateVariantsAction,\n },\n },\n }\n}\n"],"mappings":"iJAkCA,SAAgB,GAA8C,CAE1D,MAAU,MAAM,gFAAgF"}