@murumets-ee/media 0.69.0 → 0.71.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 (71) hide show
  1. package/dist/admin.d.mts.map +1 -1
  2. package/dist/admin.mjs +1 -1
  3. package/dist/client-CSOH7Zun.mjs +2 -0
  4. package/dist/client-CSOH7Zun.mjs.map +1 -0
  5. package/dist/client.d.mts +1 -1
  6. package/dist/client.d.mts.map +1 -1
  7. package/dist/client.mjs +1 -1
  8. package/dist/client.mjs.map +1 -1
  9. package/dist/crop.d.mts +2 -0
  10. package/dist/crop.mjs +1 -0
  11. package/dist/entity-CNxAERYG.mjs +2 -0
  12. package/dist/entity-CNxAERYG.mjs.map +1 -0
  13. package/dist/entity-DKFCdQJT.mjs +2 -0
  14. package/dist/entity-DKFCdQJT.mjs.map +1 -0
  15. package/dist/focal-point-BWhtJzef.mjs +2 -0
  16. package/dist/focal-point-BWhtJzef.mjs.map +1 -0
  17. package/dist/focal-point-C_0drV03.d.mts +125 -0
  18. package/dist/focal-point-C_0drV03.d.mts.map +1 -0
  19. package/dist/image-styles-settings-DEnu-V2E.mjs +2 -0
  20. package/dist/{image-styles-settings-ClIA2MJI.mjs.map → image-styles-settings-DEnu-V2E.mjs.map} +1 -1
  21. package/dist/image-styles-settings.d.mts +1 -1
  22. package/dist/image-styles-settings.mjs +1 -1
  23. package/dist/index.d.mts +1 -1
  24. package/dist/index.mjs +1 -1
  25. package/dist/picker.d.mts +107 -5
  26. package/dist/picker.d.mts.map +1 -1
  27. package/dist/picker.mjs +1 -1
  28. package/dist/picker.mjs.map +1 -1
  29. package/dist/{plugin-BkEED6qj.mjs → plugin-B_ZtfiAc.mjs} +2 -2
  30. package/dist/{plugin-BkEED6qj.mjs.map → plugin-B_ZtfiAc.mjs.map} +1 -1
  31. package/dist/plugin.d.mts +1 -1
  32. package/dist/plugin.mjs +1 -1
  33. package/dist/plugin.mjs.map +1 -1
  34. package/dist/process-image-WByEHTXQ.mjs +2 -0
  35. package/dist/process-image-WByEHTXQ.mjs.map +1 -0
  36. package/dist/processing.d.mts +1 -1
  37. package/dist/processing.d.mts.map +1 -1
  38. package/dist/processing.mjs +1 -1
  39. package/dist/public-resolver.d.mts +14 -1
  40. package/dist/public-resolver.d.mts.map +1 -1
  41. package/dist/public-resolver.mjs +1 -1
  42. package/dist/public-resolver.mjs.map +1 -1
  43. package/dist/query-client.d.mts +1 -1
  44. package/dist/query-client.mjs +1 -1
  45. package/dist/{regenerate-variants-sit6LbUo.mjs → regenerate-variants-2Lmo5kf8.mjs} +2 -2
  46. package/dist/{regenerate-variants-sit6LbUo.mjs.map → regenerate-variants-2Lmo5kf8.mjs.map} +1 -1
  47. package/dist/{regenerate-variants-BysyeIoA.mjs → regenerate-variants-B9AXXN6N.mjs} +2 -2
  48. package/dist/{regenerate-variants-BysyeIoA.mjs.map → regenerate-variants-B9AXXN6N.mjs.map} +1 -1
  49. package/dist/{resolve-image-styles-BzSRuXUs.mjs → resolve-image-styles-Cakg1Qpp.mjs} +2 -2
  50. package/dist/{resolve-image-styles-BzSRuXUs.mjs.map → resolve-image-styles-Cakg1Qpp.mjs.map} +1 -1
  51. package/dist/routes-C7Fx-055.mjs +2 -0
  52. package/dist/routes-C7Fx-055.mjs.map +1 -0
  53. package/dist/{types-1idCpe1k.d.mts → types-CnORVkLZ.d.mts} +24 -3
  54. package/dist/types-CnORVkLZ.d.mts.map +1 -0
  55. package/dist/variant-key-RKke2RfS.mjs +2 -0
  56. package/dist/variant-key-RKke2RfS.mjs.map +1 -0
  57. package/package.json +12 -8
  58. package/dist/client-YlSoGADl.mjs +0 -2
  59. package/dist/client-YlSoGADl.mjs.map +0 -1
  60. package/dist/entity-Caba_NFw.mjs +0 -2
  61. package/dist/entity-Caba_NFw.mjs.map +0 -1
  62. package/dist/entity-fxw-Qywj.mjs +0 -2
  63. package/dist/entity-fxw-Qywj.mjs.map +0 -1
  64. package/dist/image-styles-settings-ClIA2MJI.mjs +0 -2
  65. package/dist/process-image-DYDTMGUJ.mjs +0 -2
  66. package/dist/process-image-DYDTMGUJ.mjs.map +0 -1
  67. package/dist/routes-RCy0SYsK.mjs +0 -2
  68. package/dist/routes-RCy0SYsK.mjs.map +0 -1
  69. package/dist/types-1idCpe1k.d.mts.map +0 -1
  70. package/dist/variant-key-CLlac3_1.mjs +0 -2
  71. package/dist/variant-key-CLlac3_1.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"admin.d.mts","names":[],"sources":["../src/admin/routes.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;iBAqoBgB,WAAA,CAAA,GAAe,UAAU"}
1
+ {"version":3,"file":"admin.d.mts","names":[],"sources":["../src/admin/routes.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;iBA2yBgB,WAAA,CAAA,GAAe,UAAU"}
package/dist/admin.mjs CHANGED
@@ -1 +1 @@
1
- import{t as e}from"./routes-RCy0SYsK.mjs";export{e as mediaRoutes};
1
+ import{t as e}from"./routes-C7Fx-055.mjs";export{e as mediaRoutes};
@@ -0,0 +1,2 @@
1
+ import"./entity-CNxAERYG.mjs";import{i as e,n as t,r as n,t as r}from"./variant-key-RKke2RfS.mjs";import"server-only";function i(e){return e.startsWith(`image/`)?`image`:e.startsWith(`video/`)?`video`:e.startsWith(`audio/`)?`audio`:e===`application/pdf`||e.startsWith(`application/msword`)||e.startsWith(`application/vnd.`)?`document`:`other`}var a=class{admin;storage;imageStyles;constructor(e){this.admin=e.admin,this.storage=e.storage,this.imageStyles=e.imageStyles??null}async resolveImageStyles(){if(this.imageStyles)return this.imageStyles;let{getApp:e}=await import(`@murumets-ee/core`),{resolveImageStyles:t}=await import(`./resolve-image-styles-Cakg1Qpp.mjs`),n=e();return this.imageStyles=await t(n,n.logger),this.imageStyles}invalidateImageStylesCache(){this.imageStyles=null}async upload(a,c){let l=await this.storage.upload(a,{filename:c.filename,mimeType:c.mimeType,size:c.size,visibility:c.visibility,uploadedBy:c.uploadedBy}),u=c.width??null,d=c.height??null,f=null,p={};if(a instanceof Buffer&&n(c.mimeType))try{let n=await this.resolveImageStyles(),[i,o]=await Promise.all([e(a,n),t(a).catch(async e=>(await s(e,c.filename),null))]);f=o,u=i.width,d=i.height;let m=l.visibility;await Promise.all([...i.variants.entries()].map(async([e,t])=>{let n=r(l.key,e,t.format);try{await this.storage.upload(t.buffer,{key:n,filename:`${e}_${c.filename}`,mimeType:t.mimeType,size:t.buffer.byteLength,visibility:m,metadata:{variantOf:l.key,style:e},uploadedBy:c.uploadedBy}),p[e]=n}catch{}})),Object.keys(p).length>0&&await this.storage.updateMetadata(l.key,{metadata:{...l.metadata??{},variants:p}}).catch(()=>{})}catch{}let m=i(c.mimeType);try{return{media:await this.admin.create({title:c.title??o(c.filename),alt:c.alt??null,description:c.description??null,fileKey:l.key,filename:c.filename,mimeType:c.mimeType,size:c.size,width:u,height:d,focalPoint:f,mediaType:m}),url:await this.storage.getUrl(l.key)}}catch(e){for(let e of Object.values(p))await this.storage.delete(e).catch(()=>{});throw await this.storage.delete(l.key).catch(()=>{}),e}}async findById(e,t){return this.admin.findById(e,t)}async findMany(e){let{schemaRegistry:t}=await import(`@murumets-ee/db`),{and:n,asc:r,desc:i,eq:a,ilike:o,or:s,sql:c}=await import(`drizzle-orm`),l=t.get(`media`);if(!l)throw Error(`Media schema not registered. Is the media() plugin loaded?`);let u=[];if(e?.mediaType&&u.push(a(l.mediaType,e.mediaType)),e?.mimeTypePrefix){let t=e.mimeTypePrefix.replace(/[\\%_]/g,`\\$&`);u.push(o(l.mimeType,`${t}%`))}if(e?.search){let t=`%${e.search.replace(/[\\%_]/g,`\\$&`)}%`;u.push(s(o(l.filename,t),c`${l.fields} ->> 'title' ILIKE ${t}`))}let d=e?.limit??50,f=e?.offset??0,p=u.length>0?n(...u):void 0,m=await this.admin.count({where:p}),h=e?.orderBy===`filename`?l.filename:l.createdAt,g=(e?.orderDirection??`desc`)===`asc`?r:i;return{items:await this.admin.findMany({where:p,limit:d,offset:f,orderBy:g(h)}),total:m,limit:d,offset:f}}async update(e,t){return this.admin.update(e,t)}async delete(e){let t=await this.admin.findById(e);if(!t)throw Error(`Media not found: ${e}`);let n=t.fileKey;await this.admin.delete(e);let r=(await this.storage.getMetadata(n))?.metadata?.variants;if(r)for(let e of Object.values(r))await this.storage.delete(e).catch(()=>{});await this.storage.delete(n).catch(()=>{})}async getUrl(e){let t=await this.admin.findById(e);if(!t)throw Error(`Media not found: ${e}`);return this.storage.getUrl(t.fileKey)}async getUrls(e){if(e.length===0)return new Map;let{schemaRegistry:t}=await import(`@murumets-ee/db`),{inArray:n}=await import(`drizzle-orm`),r=t.get(`media`);if(!r)return new Map;let i=await this.admin.findMany({where:n(r.id,e),limit:e.length}),a=new Map;return await Promise.all(i.map(async e=>{let t=await this.storage.getUrl(e.fileKey);a.set(e.id,t)})),a}async getVariantUrl(e,t){let n=await this.admin.findById(e);if(!n)return null;let i=n.fileKey,a=(await this.resolveImageStyles())[t];if(a){let e=r(i,t,a.format??`webp`);try{return await this.storage.getUrl(e)}catch{}}try{return await this.storage.getUrl(i)}catch{return null}}async getVariantUrls(e,t){if(e.length===0)return new Map;let{schemaRegistry:n}=await import(`@murumets-ee/db`),{inArray:i}=await import(`drizzle-orm`),a=n.get(`media`);if(!a)return new Map;let o=await this.admin.findMany({where:i(a.id,e),limit:e.length}),s=(await this.resolveImageStyles())[t],c=new Map;return await Promise.all(o.map(async e=>{if(s){let n=r(e.fileKey,t,s.format??`webp`);try{let t=await this.storage.getUrl(n);c.set(e.id,t);return}catch{}}try{let t=await this.storage.getUrl(e.fileKey);c.set(e.id,t)}catch{}})),c}};function o(e){return e.replace(/\.[^.]+$/,``).replace(/[-_]/g,` `)}async function s(e,t){try{let{getApp:n}=await import(`@murumets-ee/core`);n().logger.warn({err:e,filename:t},`media: focal-point detection failed; stored as centre`)}catch(n){console.warn(`media: focal-point detection failed; stored as centre`,t,e,n)}}export{a as MediaClient};
2
+ //# sourceMappingURL=client-CSOH7Zun.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client-CSOH7Zun.mjs","names":[],"sources":["../src/async-cache.ts","../src/derive-media-type.ts","../src/client.ts"],"sourcesContent":["/**\n * Small async caching primitives shared by the media read paths.\n *\n * A LEAF module on purpose: `client.ts` needs\n * {@link cacheOnceUnlessRejected} and `public-resolver.ts` dynamically imports\n * `client.ts`, so keeping the helper in either would put a static edge across a\n * dynamic one. Both import this instead.\n *\n * Both helpers share one rule — **a rejection is never pinned**. A cached\n * failure turns one transient blip into a permanent outage that only a restart\n * clears, which is tolerable behind an admin action and is not behind the\n * anonymous request path these now serve.\n */\n\n/**\n * Cache a one-shot async initialisation — but NEVER a rejection.\n *\n * A bare `promise ??= load()` singleton pins a rejected promise for the life of\n * the process: one transient failure during initialisation and every later\n * caller replays that same rejection until restart. That is tolerable when the\n * singleton serves an admin operation someone will retry by hand; it is not\n * when it serves the anonymous request path, where the symptom is every image\n * on the site failing permanently with no way to recover short of a redeploy.\n *\n * Same rule as {@link memoiseWithTtl}, without the TTL — a success here is\n * process-lifetime by design (the value is configuration, not data).\n */\nexport function cacheOnceUnlessRejected<T>(load: () => Promise<T>): () => Promise<T> {\n let cached: Promise<T> | null = null\n return () => {\n if (cached) return cached\n const pending = load()\n cached = pending\n pending.catch(() => {\n // Only clear OUR entry — a later call may already have replaced it.\n if (cached === pending) cached = null\n })\n return pending\n }\n}\n","import type { MediaType } from './types.js'\n\n/**\n * Classify a MIME type into the coarse `MediaType` an upload is stored under.\n *\n * Pure and dependency-free, and in its own module on purpose: `client.ts`\n * (`import 'server-only'`) needs it to set `mediaType` at upload, and the admin\n * list's MIME-type cell (`picker/media-type-icon.ts`, a CLIENT entry) needs the\n * same answer to pick an icon. One rule in one file means the icon a row shows\n * cannot disagree with the type it was stored as — which two copies would, the\n * first time someone taught one of them about a new document type.\n */\nexport function deriveMediaType(mimeType: string): MediaType {\n if (mimeType.startsWith('image/')) return 'image'\n if (mimeType.startsWith('video/')) return 'video'\n if (mimeType.startsWith('audio/')) return 'audio'\n if (\n mimeType === 'application/pdf' ||\n mimeType.startsWith('application/msword') ||\n mimeType.startsWith('application/vnd.')\n ) {\n return 'document'\n }\n return 'other'\n}\n","/**\n * MediaClient — wraps AdminClient + StorageClient for media management.\n *\n * Usage:\n * import { createMediaClient } from '@murumets-ee/media/client'\n * const media = await createMediaClient(storageClient)\n * const result = await media.upload(buffer, { filename: 'photo.jpg', mimeType: 'image/jpeg', size: 12345 })\n */\n\nimport 'server-only'\n\nimport type { AdminClient } from '@murumets-ee/entity/admin'\nimport type { StorageClient } from '@murumets-ee/storage'\nimport { cacheOnceUnlessRejected } from './async-cache.js'\nimport type { FocalPoint } from './crop/focal-point.js'\nimport { deriveMediaType } from './derive-media-type.js'\nimport { Media } from './entity.js'\nimport { detectFocalPoint, isProcessableImage, processImage } from './process-image.js'\nimport type {\n ImageStyle,\n MediaListOptions,\n MediaListResult,\n MediaRecord,\n MediaUploadOptions,\n MediaUploadResult,\n} from './types.js'\nimport { deriveVariantKey } from './variant-key.js'\n\ntype MediaFields = typeof Media.allFields\n\nexport interface MediaClientConfig {\n admin: AdminClient<MediaFields>\n storage: StorageClient\n /** Image styles to generate on upload. Loaded from plugin config if not provided. */\n imageStyles?: Record<string, ImageStyle>\n}\n\nexport class MediaClient {\n private admin: AdminClient<MediaFields>\n private storage: StorageClient\n private imageStyles: Record<string, ImageStyle> | null\n\n constructor(config: MediaClientConfig) {\n this.admin = config.admin\n this.storage = config.storage\n this.imageStyles = config.imageStyles ?? null\n }\n\n /**\n * Resolve image styles via the shared waterfall (settings DB → plugin\n * config → hardcoded defaults) and cache the result on this instance.\n * Call `invalidateImageStylesCache()` after a settings update.\n */\n private async resolveImageStyles(): Promise<Record<string, ImageStyle>> {\n if (this.imageStyles) return this.imageStyles\n const { getApp } = await import('@murumets-ee/core')\n const { resolveImageStyles } = await import('./resolve-image-styles.js')\n const app = getApp()\n this.imageStyles = await resolveImageStyles(app, app.logger)\n return this.imageStyles\n }\n\n /** Clear cached styles so next access re-reads from settings DB. */\n invalidateImageStylesCache(): void {\n this.imageStyles = null\n }\n\n // ---------------------------------------------------------------\n // Upload — the key convenience method\n // ---------------------------------------------------------------\n\n /**\n * Upload a file and create a media entity record in one step.\n * 1. Uploads original to storage (StorageClient)\n * 2. If image: extracts dimensions via Sharp + generates variants\n * 3. Creates media entity record (AdminClient)\n * 4. Returns the media record + URL\n *\n * Rolls back storage upload if entity creation fails.\n * Variant generation failures are logged but don't fail the upload.\n */\n async upload(\n data: Buffer | ReadableStream<Uint8Array>,\n options: MediaUploadOptions,\n ): Promise<MediaUploadResult> {\n // 1. Upload original file to storage\n const fileRecord = await this.storage.upload(data, {\n filename: options.filename,\n mimeType: options.mimeType,\n size: options.size,\n visibility: options.visibility,\n uploadedBy: options.uploadedBy,\n })\n\n // 2. Image processing — extract dimensions + generate variants\n let width = options.width ?? null\n let height = options.height ?? null\n // `null` renders as the centre (images D010), so a failed or skipped guess\n // is exactly today's crop rather than an error.\n let focalPoint: FocalPoint | null = null\n const variantKeys: Record<string, string> = {}\n\n if (data instanceof Buffer && isProcessableImage(options.mimeType)) {\n try {\n const styles = await this.resolveImageStyles()\n // The focal-point seed runs beside the variants rather than after them —\n // two independent sharp passes over the same buffer. Its own failure is\n // swallowed here so a photograph the attention pass cannot read still\n // gets its variants.\n const [processed, seeded] = await Promise.all([\n processImage(data, styles),\n detectFocalPoint(data).catch(async (err: unknown) => {\n await warnFocalPointFailed(err, options.filename)\n return null\n }),\n ])\n focalPoint = seeded\n\n // Set dimensions from Sharp metadata\n width = processed.width\n height = processed.height\n\n // Upload each variant to storage\n const visibility = fileRecord.visibility\n await Promise.all(\n [...processed.variants.entries()].map(async ([styleName, variant]) => {\n const vKey = deriveVariantKey(fileRecord.key, styleName, variant.format)\n try {\n await this.storage.upload(variant.buffer, {\n key: vKey,\n filename: `${styleName}_${options.filename}`,\n mimeType: variant.mimeType,\n size: variant.buffer.byteLength,\n visibility,\n metadata: { variantOf: fileRecord.key, style: styleName },\n uploadedBy: options.uploadedBy,\n })\n variantKeys[styleName] = vKey\n } catch {\n // Variant upload failure is non-fatal — original is saved\n }\n }),\n )\n\n // Store variant keys in original file's metadata\n if (Object.keys(variantKeys).length > 0) {\n await this.storage\n .updateMetadata(fileRecord.key, {\n metadata: {\n ...(fileRecord.metadata ?? {}),\n variants: variantKeys,\n },\n })\n .catch(() => {\n // Metadata update failure is non-fatal\n })\n }\n } catch {\n // Image processing failure is non-fatal — original is saved\n }\n }\n\n // 3. Create media entity record\n const mediaType = deriveMediaType(options.mimeType)\n\n try {\n const entityRecord = await this.admin.create({\n title: options.title ?? deriveTitle(options.filename),\n alt: options.alt ?? null,\n description: options.description ?? null,\n fileKey: fileRecord.key,\n filename: options.filename,\n mimeType: options.mimeType,\n size: options.size,\n width,\n height,\n focalPoint,\n mediaType,\n })\n\n // 4. Get URL\n const url = await this.storage.getUrl(fileRecord.key)\n\n return {\n media: entityRecord,\n url,\n }\n } catch (error) {\n // Rollback: delete variants + original if entity creation fails\n\n // Delete variants first (best-effort)\n for (const vKey of Object.values(variantKeys)) {\n await this.storage.delete(vKey).catch(() => {})\n }\n\n // Delete original\n await this.storage.delete(fileRecord.key).catch(() => {\n // Storage rollback failure is already being handled — propagate original error\n })\n throw error\n }\n }\n\n // ---------------------------------------------------------------\n // CRUD delegation\n // ---------------------------------------------------------------\n\n async findById(id: string, options?: { locale?: string }): Promise<MediaRecord | null> {\n return this.admin.findById(id, options)\n }\n\n async findMany(options?: MediaListOptions): Promise<MediaListResult> {\n const { schemaRegistry } = await import('@murumets-ee/db')\n const { and, asc, desc, eq, ilike, or, sql } = await import('drizzle-orm')\n\n const table = schemaRegistry.get('media')\n if (!table) throw new Error('Media schema not registered. Is the media() plugin loaded?')\n\n // Build where conditions\n const conditions = []\n\n if (options?.mediaType) {\n conditions.push(eq(table.mediaType, options.mediaType))\n }\n if (options?.mimeTypePrefix) {\n // Escape ILIKE wildcards (%, _) in user input to prevent pattern injection\n const escaped = options.mimeTypePrefix.replace(/[\\\\%_]/g, '\\\\$&')\n conditions.push(ilike(table.mimeType, `${escaped}%`))\n }\n if (options?.search) {\n // Escape ILIKE wildcards in user input, then wrap with %...%\n const escaped = options.search.replace(/[\\\\%_]/g, '\\\\$&')\n const pattern = `%${escaped}%`\n conditions.push(\n or(\n ilike(table.filename, pattern),\n sql`${table.fields} ->> 'title' ILIKE ${pattern}`,\n )!,\n )\n }\n\n const limit = options?.limit ?? 50\n const offset = options?.offset ?? 0\n const whereClause = conditions.length > 0 ? and(...conditions) : undefined\n\n // Count total via AdminClient\n const total = await this.admin.count({ where: whereClause })\n\n // Fetch items via AdminClient for proper DTO shaping\n const orderField = options?.orderBy === 'filename' ? table.filename : table.createdAt\n const orderFn = (options?.orderDirection ?? 'desc') === 'asc' ? asc : desc\n\n const items = await this.admin.findMany({\n where: whereClause,\n limit,\n offset,\n orderBy: orderFn(orderField),\n })\n\n return {\n items,\n total,\n limit,\n offset,\n }\n }\n\n async update(\n id: string,\n data: { title?: string; alt?: string; description?: string },\n ): Promise<MediaRecord> {\n return this.admin.update(id, data)\n }\n\n /**\n * Delete a media entity, its variants, and its original file in storage.\n */\n async delete(id: string): Promise<void> {\n const record = await this.admin.findById(id)\n if (!record) throw new Error(`Media not found: ${id}`)\n\n const fileKey = record.fileKey\n\n // 1. Delete entity first (ref checking via entity_refs happens here)\n await this.admin.delete(id)\n\n // 2. Look up original file record for variant metadata\n const fileRecord = await this.storage.getMetadata(fileKey)\n const variants = (fileRecord?.metadata as Record<string, unknown> | null)?.variants as\n | Record<string, string>\n | undefined\n\n // 3. Delete variants (best-effort)\n if (variants) {\n for (const vKey of Object.values(variants)) {\n await this.storage.delete(vKey).catch(() => {\n // Variant deletion failure is non-fatal\n })\n }\n }\n\n // 4. Delete original file (best-effort)\n await this.storage.delete(fileKey).catch(() => {\n // Storage deletion failure is non-fatal — entity is already deleted\n })\n }\n\n // ---------------------------------------------------------------\n // URL resolution\n // ---------------------------------------------------------------\n\n /**\n * Get URL for a media entity by its ID.\n * Resolves entity -> fileKey -> storage URL.\n */\n async getUrl(id: string): Promise<string> {\n const record = await this.admin.findById(id)\n if (!record) throw new Error(`Media not found: ${id}`)\n\n return this.storage.getUrl(record.fileKey)\n }\n\n /**\n * Get URLs for multiple media entities (batch).\n * Returns a Map of mediaId -> url.\n */\n async getUrls(ids: string[]): Promise<Map<string, string>> {\n if (ids.length === 0) return new Map()\n\n const { schemaRegistry } = await import('@murumets-ee/db')\n const { inArray } = await import('drizzle-orm')\n\n const table = schemaRegistry.get('media')\n if (!table) return new Map()\n\n const records = await this.admin.findMany({\n where: inArray(table.id, ids),\n limit: ids.length,\n })\n\n const urlMap = new Map<string, string>()\n\n await Promise.all(\n records.map(async (record) => {\n const url = await this.storage.getUrl(record.fileKey)\n urlMap.set(record.id, url)\n }),\n )\n\n return urlMap\n }\n\n /**\n * Get variant URL for a specific image style.\n * Falls back to original URL if the variant doesn't exist.\n *\n * @param id - Media entity ID\n * @param styleName - Image style name (e.g., 'thumbnail')\n * @returns The variant URL, or original URL as fallback, or null if media not found\n */\n async getVariantUrl(id: string, styleName: string): Promise<string | null> {\n const record = await this.admin.findById(id)\n if (!record) return null\n\n const fileKey = record.fileKey\n\n // Try variant key first\n const styles = await this.resolveImageStyles()\n const style = styles[styleName]\n if (style) {\n const vKey = deriveVariantKey(fileKey, styleName, style.format ?? 'webp')\n try {\n return await this.storage.getUrl(vKey)\n } catch {\n // Variant doesn't exist — fall back to original\n }\n }\n\n // Fallback to original\n try {\n return await this.storage.getUrl(fileKey)\n } catch {\n return null\n }\n }\n\n /**\n * Get variant URLs for multiple media entities (batch).\n * Falls back to original URL per item if the variant doesn't exist.\n *\n * @param ids - Media entity IDs\n * @param styleName - Image style name (e.g., 'thumbnail')\n * @returns Map of mediaId -> variant URL (or original URL as fallback)\n */\n async getVariantUrls(ids: string[], styleName: string): Promise<Map<string, string>> {\n if (ids.length === 0) return new Map()\n\n const { schemaRegistry } = await import('@murumets-ee/db')\n const { inArray } = await import('drizzle-orm')\n\n const table = schemaRegistry.get('media')\n if (!table) return new Map()\n\n const records = await this.admin.findMany({\n where: inArray(table.id, ids),\n limit: ids.length,\n })\n\n const styles = await this.resolveImageStyles()\n const style = styles[styleName]\n const urlMap = new Map<string, string>()\n\n await Promise.all(\n records.map(async (record) => {\n // Try variant URL\n if (style) {\n const vKey = deriveVariantKey(record.fileKey, styleName, style.format ?? 'webp')\n try {\n const url = await this.storage.getUrl(vKey)\n urlMap.set(record.id, url)\n return\n } catch {\n // Variant doesn't exist — fall back to original\n }\n }\n\n // Fallback to original\n try {\n const url = await this.storage.getUrl(record.fileKey)\n urlMap.set(record.id, url)\n } catch {\n // Skip — no URL available\n }\n }),\n )\n\n return urlMap\n }\n}\n\n// ---------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------\n\nfunction deriveTitle(filename: string): string {\n const withoutExt = filename.replace(/\\.[^.]+$/, '')\n return withoutExt.replace(/[-_]/g, ' ')\n}\n\n/**\n * Factory — creates a MediaClient with an explicit StorageClient.\n * Must be called after createApp().\n */\nexport async function createMediaClient(storage: StorageClient): Promise<MediaClient> {\n const { createAdminClient } = await import('@murumets-ee/core/clients')\n const admin = createAdminClient(Media)\n return new MediaClient({ admin, storage })\n}\n\n// ---------------------------------------------------------------------------\n// Per-request MediaClient factory\n// ---------------------------------------------------------------------------\n//\n// NOTE: Storage config is process-global and safe to cache.\n// MediaClient / AdminClient must be built per-request — they carry a\n// context resolver tied to the calling request's user + permissions.\n// A singleton would leak one request's security context across others.\n\n/**\n * The storage singleton, which does NOT pin a failed initialisation.\n *\n * `_storagePromise ??= (...)()` used to cache the rejected promise too, so a\n * transient failure during storage init (config not yet loaded, a DB blip)\n * broke every subsequent caller until the process restarted. That mattered\n * little while this served admin operations; `plan/api` PR 5 puts it on the\n * ANONYMOUS request path via `getSharedStorageClient`, where the symptom\n * becomes every image on the site failing permanently with no recovery short of\n * a redeploy. See `cacheOnceUnlessRejected`, which is unit-tested.\n */\nconst _storageOnce = cacheOnceUnlessRejected<StorageClient>(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/**\n * The process-wide `StorageClient`, built once from the storage plugin config.\n *\n * Exported so the PUBLIC media resolver (`./public-resolver.ts`) reaches the\n * same instance rather than constructing a second one from a copy of these two\n * lines. Safe to share, and unlike `MediaClient`/`AdminClient` it MUST NOT be\n * rebuilt per request: it carries no security context — the read-side gate\n * lives in whichever client resolves the media rows, not here.\n */\nexport async function getSharedStorageClient(): Promise<StorageClient> {\n return getStorageSingleton()\n}\n\nasync function getStorageSingleton(): Promise<StorageClient> {\n return _storageOnce()\n}\n\n/**\n * Returns a fresh MediaClient wired to the current request's context.\n * Must be called after createApp(), inside a request context\n * (withAdminContext, runAsCli, etc.).\n *\n * Despite the name, this is NOT cached — the storage config is cached\n * internally but the MediaClient and its AdminClient are rebuilt per call\n * so the security context resolver attaches to the correct request.\n */\nexport async function getMediaClient(): Promise<MediaClient> {\n const { createAdminClient } = await import('@murumets-ee/core/clients')\n const storage = await getStorageSingleton()\n const admin = createAdminClient(Media)\n return new MediaClient({ admin, storage })\n}\n\n/**\n * A failed focal-point guess is not an upload failure — the row is stored with\n * `null`, which renders as the centre (D010) — but it is not silent either: a\n * decoder that cannot read a whole format would otherwise leave every such\n * photograph centred with nothing saying why.\n */\nasync function warnFocalPointFailed(err: unknown, filename: string): Promise<void> {\n try {\n const { getApp } = await import('@murumets-ee/core')\n getApp().logger.warn({ err, filename }, 'media: focal-point detection failed; stored as centre')\n } catch (loggerErr) {\n // No app (a script, a test) — fall back to the console rather than lose it.\n console.warn('media: focal-point detection failed; stored as centre', filename, err, loggerErr)\n }\n}\n"],"mappings":"sHCYA,SAAgB,EAAgB,EAA6B,CAW3D,OAVI,EAAS,WAAW,QAAQ,EAAU,QACtC,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AChC,EAAO,CAAC,CAAC,OAAO,KAAK,CAAE,MAAK,UAAS,EAAG,uDAAuD,CACjG,OAAS,EAAW,CAElB,QAAQ,KAAK,wDAAyD,EAAU,EAAK,CAAS,CAChG,CACF"}
package/dist/client.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { a as MediaRecord, c as MediaUploadResult, l as Media, n as MediaListOptions, r as MediaListResult, s as MediaUploadOptions, t as ImageStyle } from "./types-1idCpe1k.mjs";
1
+ import { a as MediaRecord, c as MediaUploadResult, l as Media, n as MediaListOptions, r as MediaListResult, s as MediaUploadOptions, t as ImageStyle } from "./types-CnORVkLZ.mjs";
2
2
  import { AdminClient } from "@murumets-ee/entity/admin";
3
3
  import { StorageClient } from "@murumets-ee/storage";
4
4
 
@@ -1 +1 @@
1
- {"version":3,"file":"client.d.mts","names":[],"sources":["../src/client.ts"],"mappings":";;;;;KA2BK,WAAA,UAAqB,KAAA,CAAM,SAAS;AAAA,UAExB,iBAAA;EACf,KAAA,EAAO,WAAA,CAAY,WAAA;EACnB,OAAA,EAAS,aAAA;EAEoB;EAA7B,WAAA,GAAc,MAAA,SAAe,UAAA;AAAA;AAAA,cAGlB,WAAA;EAAA,QACH,KAAA;EAAA,QACA,OAAA;EAAA,QACA,WAAA;cAEI,MAAA,EAAQ,iBAAA;EAVX;;;;;EAAA,QAqBK,kBAAA;EAhBH;EA0BX,0BAAA,CAAA;;;;;;;;;;;EAkBM,MAAA,CACJ,IAAA,EAAM,MAAA,GAAS,cAAA,CAAe,UAAA,GAC9B,OAAA,EAAS,kBAAA,GACR,OAAA,CAAQ,iBAAA;EA4GL,QAAA,CAAS,EAAA,UAAY,OAAA;IAAY,MAAA;EAAA,IAAoB,OAAA,CAAQ,WAAA;EAI7D,QAAA,CAAS,OAAA,GAAU,gBAAA,GAAmB,OAAA,CAAQ,eAAA;EAwD9C,MAAA,CACJ,EAAA,UACA,IAAA;IAAQ,KAAA;IAAgB,GAAA;IAAc,WAAA;EAAA,IACrC,OAA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,GAAA;IAAc,WAAA;EAAA,IACrC,OAAA,CAAQ,WAAA;EA4HqD;;;EArH1D,MAAA,CAAO,EAAA,WAAa,OAAA;EA/OlB;;;;EAqRF,MAAA,CAAO,EAAA,WAAa,OAAA;EAjRd;;;;EA4RN,OAAA,CAAQ,GAAA,aAAgB,OAAA,CAAQ,GAAA;EApPrB;;;;;;;;EAsRX,aAAA,CAAc,EAAA,UAAY,SAAA,WAAoB,OAAA;EAzJb;;;;;;;;EA2LjC,cAAA,CAAe,GAAA,YAAe,SAAA,WAAoB,OAAA,CAAQ,GAAA;AAAA;;;;;iBA2D5C,iBAAA,CAAkB,OAAA,EAAS,aAAA,GAAgB,OAAA,CAAQ,WAAA;;;;;;;;;;iBA2CnD,sBAAA,CAAA,GAA0B,OAAO,CAAC,aAAA;;;;;;;;;;iBAiBlC,cAAA,CAAA,GAAkB,OAAO,CAAC,WAAA"}
package/dist/client.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import{t as e}from"./entity-fxw-Qywj.mjs";import{t}from"./async-cache-C_Ycvs7b.mjs";import{n,r}from"./process-image-DYDTMGUJ.mjs";import{t as i}from"./variant-key-JBTJXPL1.mjs";import"server-only";var a=class{admin;storage;imageStyles;constructor(e){this.admin=e.admin,this.storage=e.storage,this.imageStyles=e.imageStyles??null}async resolveImageStyles(){if(this.imageStyles)return this.imageStyles;let{getApp:e}=await import(`@murumets-ee/core`),{resolveImageStyles:t}=await import(`./resolve-image-styles-iN9JbZYf.mjs`),n=e();return this.imageStyles=await t(n,n.logger),this.imageStyles}invalidateImageStylesCache(){this.imageStyles=null}async upload(e,t){let a=await this.storage.upload(e,{filename:t.filename,mimeType:t.mimeType,size:t.size,visibility:t.visibility,uploadedBy:t.uploadedBy}),c=t.width??null,l=t.height??null,u={};if(e instanceof Buffer&&n(t.mimeType))try{let n=await r(e,await this.resolveImageStyles());c=n.width,l=n.height;let o=a.visibility;await Promise.all([...n.variants.entries()].map(async([e,n])=>{let r=i(a.key,e,n.format);try{await this.storage.upload(n.buffer,{key:r,filename:`${e}_${t.filename}`,mimeType:n.mimeType,size:n.buffer.byteLength,visibility:o,metadata:{variantOf:a.key,style:e},uploadedBy:t.uploadedBy}),u[e]=r}catch{}})),Object.keys(u).length>0&&await this.storage.updateMetadata(a.key,{metadata:{...a.metadata??{},variants:u}}).catch(()=>{})}catch{}let d=o(t.mimeType);try{return{media:await this.admin.create({title:t.title??s(t.filename),alt:t.alt??null,description:t.description??null,fileKey:a.key,filename:t.filename,mimeType:t.mimeType,size:t.size,width:c,height:l,mediaType:d}),url:await this.storage.getUrl(a.key)}}catch(e){for(let e of Object.values(u))await this.storage.delete(e).catch(()=>{});throw await this.storage.delete(a.key).catch(()=>{}),e}}async findById(e,t){return this.admin.findById(e,t)}async findMany(e){let{schemaRegistry:t}=await import(`@murumets-ee/db`),{and:n,asc:r,desc:i,eq:a,ilike:o,or:s,sql:c}=await import(`drizzle-orm`),l=t.get(`media`);if(!l)throw Error(`Media schema not registered. Is the media() plugin loaded?`);let u=[];if(e?.mediaType&&u.push(a(l.mediaType,e.mediaType)),e?.mimeTypePrefix){let t=e.mimeTypePrefix.replace(/[\\%_]/g,`\\$&`);u.push(o(l.mimeType,`${t}%`))}if(e?.search){let t=`%${e.search.replace(/[\\%_]/g,`\\$&`)}%`;u.push(s(o(l.filename,t),c`${l.fields} ->> 'title' ILIKE ${t}`))}let d=e?.limit??50,f=e?.offset??0,p=u.length>0?n(...u):void 0,m=await this.admin.count({where:p}),h=e?.orderBy===`filename`?l.filename:l.createdAt,g=(e?.orderDirection??`desc`)===`asc`?r:i;return{items:await this.admin.findMany({where:p,limit:d,offset:f,orderBy:g(h)}),total:m,limit:d,offset:f}}async update(e,t){return this.admin.update(e,t)}async delete(e){let t=await this.admin.findById(e);if(!t)throw Error(`Media not found: ${e}`);let n=t.fileKey;await this.admin.delete(e);let r=(await this.storage.getMetadata(n))?.metadata?.variants;if(r)for(let e of Object.values(r))await this.storage.delete(e).catch(()=>{});await this.storage.delete(n).catch(()=>{})}async getUrl(e){let t=await this.admin.findById(e);if(!t)throw Error(`Media not found: ${e}`);return this.storage.getUrl(t.fileKey)}async getUrls(e){if(e.length===0)return new Map;let{schemaRegistry:t}=await import(`@murumets-ee/db`),{inArray:n}=await import(`drizzle-orm`),r=t.get(`media`);if(!r)return new Map;let i=await this.admin.findMany({where:n(r.id,e),limit:e.length}),a=new Map;return await Promise.all(i.map(async e=>{let t=await this.storage.getUrl(e.fileKey);a.set(e.id,t)})),a}async getVariantUrl(e,t){let n=await this.admin.findById(e);if(!n)return null;let r=n.fileKey,a=(await this.resolveImageStyles())[t];if(a){let e=i(r,t,a.format??`webp`);try{return await this.storage.getUrl(e)}catch{}}try{return await this.storage.getUrl(r)}catch{return null}}async getVariantUrls(e,t){if(e.length===0)return new Map;let{schemaRegistry:n}=await import(`@murumets-ee/db`),{inArray:r}=await import(`drizzle-orm`),a=n.get(`media`);if(!a)return new Map;let o=await this.admin.findMany({where:r(a.id,e),limit:e.length}),s=(await this.resolveImageStyles())[t],c=new Map;return await Promise.all(o.map(async e=>{if(s){let n=i(e.fileKey,t,s.format??`webp`);try{let t=await this.storage.getUrl(n);c.set(e.id,t);return}catch{}}try{let t=await this.storage.getUrl(e.fileKey);c.set(e.id,t)}catch{}})),c}};function o(e){return e.startsWith(`image/`)?`image`:e.startsWith(`video/`)?`video`:e.startsWith(`audio/`)?`audio`:e===`application/pdf`||e.startsWith(`application/msword`)||e.startsWith(`application/vnd.`)?`document`:`other`}function s(e){return e.replace(/\.[^.]+$/,``).replace(/[-_]/g,` `)}async function c(t){let{createAdminClient:n}=await import(`@murumets-ee/core/clients`);return new a({admin:n(e),storage:t})}const l=t(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})});async function u(){return d()}async function d(){return l()}async function f(){let{createAdminClient:t}=await import(`@murumets-ee/core/clients`),n=await d();return new a({admin:t(e),storage:n})}export{a as MediaClient,c as createMediaClient,f as getMediaClient,u as getSharedStorageClient};
1
+ import{t as e}from"./entity-DKFCdQJT.mjs";import{t}from"./async-cache-C_Ycvs7b.mjs";import{i as n,r,t as i}from"./process-image-WByEHTXQ.mjs";import{t as a}from"./variant-key-JBTJXPL1.mjs";import"server-only";function o(e){return e.startsWith(`image/`)?`image`:e.startsWith(`video/`)?`video`:e.startsWith(`audio/`)?`audio`:e===`application/pdf`||e.startsWith(`application/msword`)||e.startsWith(`application/vnd.`)?`document`:`other`}var s=class{admin;storage;imageStyles;constructor(e){this.admin=e.admin,this.storage=e.storage,this.imageStyles=e.imageStyles??null}async resolveImageStyles(){if(this.imageStyles)return this.imageStyles;let{getApp:e}=await import(`@murumets-ee/core`),{resolveImageStyles:t}=await import(`./resolve-image-styles-iN9JbZYf.mjs`),n=e();return this.imageStyles=await t(n,n.logger),this.imageStyles}invalidateImageStylesCache(){this.imageStyles=null}async upload(e,t){let s=await this.storage.upload(e,{filename:t.filename,mimeType:t.mimeType,size:t.size,visibility:t.visibility,uploadedBy:t.uploadedBy}),l=t.width??null,u=t.height??null,d=null,f={};if(e instanceof Buffer&&r(t.mimeType))try{let r=await this.resolveImageStyles(),[o,c]=await Promise.all([n(e,r),i(e).catch(async e=>(await m(e,t.filename),null))]);d=c,l=o.width,u=o.height;let p=s.visibility;await Promise.all([...o.variants.entries()].map(async([e,n])=>{let r=a(s.key,e,n.format);try{await this.storage.upload(n.buffer,{key:r,filename:`${e}_${t.filename}`,mimeType:n.mimeType,size:n.buffer.byteLength,visibility:p,metadata:{variantOf:s.key,style:e},uploadedBy:t.uploadedBy}),f[e]=r}catch{}})),Object.keys(f).length>0&&await this.storage.updateMetadata(s.key,{metadata:{...s.metadata??{},variants:f}}).catch(()=>{})}catch{}let p=o(t.mimeType);try{return{media:await this.admin.create({title:t.title??c(t.filename),alt:t.alt??null,description:t.description??null,fileKey:s.key,filename:t.filename,mimeType:t.mimeType,size:t.size,width:l,height:u,focalPoint:d,mediaType:p}),url:await this.storage.getUrl(s.key)}}catch(e){for(let e of Object.values(f))await this.storage.delete(e).catch(()=>{});throw await this.storage.delete(s.key).catch(()=>{}),e}}async findById(e,t){return this.admin.findById(e,t)}async findMany(e){let{schemaRegistry:t}=await import(`@murumets-ee/db`),{and:n,asc:r,desc:i,eq:a,ilike:o,or:s,sql:c}=await import(`drizzle-orm`),l=t.get(`media`);if(!l)throw Error(`Media schema not registered. Is the media() plugin loaded?`);let u=[];if(e?.mediaType&&u.push(a(l.mediaType,e.mediaType)),e?.mimeTypePrefix){let t=e.mimeTypePrefix.replace(/[\\%_]/g,`\\$&`);u.push(o(l.mimeType,`${t}%`))}if(e?.search){let t=`%${e.search.replace(/[\\%_]/g,`\\$&`)}%`;u.push(s(o(l.filename,t),c`${l.fields} ->> 'title' ILIKE ${t}`))}let d=e?.limit??50,f=e?.offset??0,p=u.length>0?n(...u):void 0,m=await this.admin.count({where:p}),h=e?.orderBy===`filename`?l.filename:l.createdAt,g=(e?.orderDirection??`desc`)===`asc`?r:i;return{items:await this.admin.findMany({where:p,limit:d,offset:f,orderBy:g(h)}),total:m,limit:d,offset:f}}async update(e,t){return this.admin.update(e,t)}async delete(e){let t=await this.admin.findById(e);if(!t)throw Error(`Media not found: ${e}`);let n=t.fileKey;await this.admin.delete(e);let r=(await this.storage.getMetadata(n))?.metadata?.variants;if(r)for(let e of Object.values(r))await this.storage.delete(e).catch(()=>{});await this.storage.delete(n).catch(()=>{})}async getUrl(e){let t=await this.admin.findById(e);if(!t)throw Error(`Media not found: ${e}`);return this.storage.getUrl(t.fileKey)}async getUrls(e){if(e.length===0)return new Map;let{schemaRegistry:t}=await import(`@murumets-ee/db`),{inArray:n}=await import(`drizzle-orm`),r=t.get(`media`);if(!r)return new Map;let i=await this.admin.findMany({where:n(r.id,e),limit:e.length}),a=new Map;return await Promise.all(i.map(async e=>{let t=await this.storage.getUrl(e.fileKey);a.set(e.id,t)})),a}async getVariantUrl(e,t){let n=await this.admin.findById(e);if(!n)return null;let r=n.fileKey,i=(await this.resolveImageStyles())[t];if(i){let e=a(r,t,i.format??`webp`);try{return await this.storage.getUrl(e)}catch{}}try{return await this.storage.getUrl(r)}catch{return null}}async getVariantUrls(e,t){if(e.length===0)return new Map;let{schemaRegistry:n}=await import(`@murumets-ee/db`),{inArray:r}=await import(`drizzle-orm`),i=n.get(`media`);if(!i)return new Map;let o=await this.admin.findMany({where:r(i.id,e),limit:e.length}),s=(await this.resolveImageStyles())[t],c=new Map;return await Promise.all(o.map(async e=>{if(s){let n=a(e.fileKey,t,s.format??`webp`);try{let t=await this.storage.getUrl(n);c.set(e.id,t);return}catch{}}try{let t=await this.storage.getUrl(e.fileKey);c.set(e.id,t)}catch{}})),c}};function c(e){return e.replace(/\.[^.]+$/,``).replace(/[-_]/g,` `)}async function l(t){let{createAdminClient:n}=await import(`@murumets-ee/core/clients`);return new s({admin:n(e),storage:t})}const u=t(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})});async function d(){return f()}async function f(){return u()}async function p(){let{createAdminClient:t}=await import(`@murumets-ee/core/clients`),n=await f();return new s({admin:t(e),storage:n})}async function m(e,t){try{let{getApp:n}=await import(`@murumets-ee/core`);n().logger.warn({err:e,filename:t},`media: focal-point detection failed; stored as centre`)}catch(n){console.warn(`media: focal-point detection failed; stored as centre`,t,e,n)}}export{s as MediaClient,l as createMediaClient,p as getMediaClient,d as getSharedStorageClient};
2
2
  //# sourceMappingURL=client.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"client.mjs","names":[],"sources":["../src/client.ts"],"sourcesContent":["/**\n * MediaClient — wraps AdminClient + StorageClient for media management.\n *\n * Usage:\n * import { createMediaClient } from '@murumets-ee/media/client'\n * const media = await createMediaClient(storageClient)\n * const result = await media.upload(buffer, { filename: 'photo.jpg', mimeType: 'image/jpeg', size: 12345 })\n */\n\nimport 'server-only'\n\nimport type { AdminClient } from '@murumets-ee/entity/admin'\nimport type { StorageClient } from '@murumets-ee/storage'\nimport { cacheOnceUnlessRejected } from './async-cache.js'\nimport { Media } from './entity.js'\nimport { isProcessableImage, processImage } from './process-image.js'\nimport type {\n ImageStyle,\n MediaListOptions,\n MediaListResult,\n MediaRecord,\n MediaType,\n MediaUploadOptions,\n MediaUploadResult,\n} from './types.js'\nimport { deriveVariantKey } from './variant-key.js'\n\ntype MediaFields = typeof Media.allFields\n\nexport interface MediaClientConfig {\n admin: AdminClient<MediaFields>\n storage: StorageClient\n /** Image styles to generate on upload. Loaded from plugin config if not provided. */\n imageStyles?: Record<string, ImageStyle>\n}\n\nexport class MediaClient {\n private admin: AdminClient<MediaFields>\n private storage: StorageClient\n private imageStyles: Record<string, ImageStyle> | null\n\n constructor(config: MediaClientConfig) {\n this.admin = config.admin\n this.storage = config.storage\n this.imageStyles = config.imageStyles ?? null\n }\n\n /**\n * Resolve image styles via the shared waterfall (settings DB → plugin\n * config → hardcoded defaults) and cache the result on this instance.\n * Call `invalidateImageStylesCache()` after a settings update.\n */\n private async resolveImageStyles(): Promise<Record<string, ImageStyle>> {\n if (this.imageStyles) return this.imageStyles\n const { getApp } = await import('@murumets-ee/core')\n const { resolveImageStyles } = await import('./resolve-image-styles.js')\n const app = getApp()\n this.imageStyles = await resolveImageStyles(app, app.logger)\n return this.imageStyles\n }\n\n /** Clear cached styles so next access re-reads from settings DB. */\n invalidateImageStylesCache(): void {\n this.imageStyles = null\n }\n\n // ---------------------------------------------------------------\n // Upload — the key convenience method\n // ---------------------------------------------------------------\n\n /**\n * Upload a file and create a media entity record in one step.\n * 1. Uploads original to storage (StorageClient)\n * 2. If image: extracts dimensions via Sharp + generates variants\n * 3. Creates media entity record (AdminClient)\n * 4. Returns the media record + URL\n *\n * Rolls back storage upload if entity creation fails.\n * Variant generation failures are logged but don't fail the upload.\n */\n async upload(\n data: Buffer | ReadableStream<Uint8Array>,\n options: MediaUploadOptions,\n ): Promise<MediaUploadResult> {\n // 1. Upload original file to storage\n const fileRecord = await this.storage.upload(data, {\n filename: options.filename,\n mimeType: options.mimeType,\n size: options.size,\n visibility: options.visibility,\n uploadedBy: options.uploadedBy,\n })\n\n // 2. Image processing — extract dimensions + generate variants\n let width = options.width ?? null\n let height = options.height ?? null\n const variantKeys: Record<string, string> = {}\n\n if (data instanceof Buffer && isProcessableImage(options.mimeType)) {\n try {\n const styles = await this.resolveImageStyles()\n const processed = await processImage(data, styles)\n\n // Set dimensions from Sharp metadata\n width = processed.width\n height = processed.height\n\n // Upload each variant to storage\n const visibility = fileRecord.visibility\n await Promise.all(\n [...processed.variants.entries()].map(async ([styleName, variant]) => {\n const vKey = deriveVariantKey(fileRecord.key, styleName, variant.format)\n try {\n await this.storage.upload(variant.buffer, {\n key: vKey,\n filename: `${styleName}_${options.filename}`,\n mimeType: variant.mimeType,\n size: variant.buffer.byteLength,\n visibility,\n metadata: { variantOf: fileRecord.key, style: styleName },\n uploadedBy: options.uploadedBy,\n })\n variantKeys[styleName] = vKey\n } catch {\n // Variant upload failure is non-fatal — original is saved\n }\n }),\n )\n\n // Store variant keys in original file's metadata\n if (Object.keys(variantKeys).length > 0) {\n await this.storage\n .updateMetadata(fileRecord.key, {\n metadata: {\n ...(fileRecord.metadata ?? {}),\n variants: variantKeys,\n },\n })\n .catch(() => {\n // Metadata update failure is non-fatal\n })\n }\n } catch {\n // Image processing failure is non-fatal — original is saved\n }\n }\n\n // 3. Create media entity record\n const mediaType = deriveMediaType(options.mimeType)\n\n try {\n const entityRecord = await this.admin.create({\n title: options.title ?? deriveTitle(options.filename),\n alt: options.alt ?? null,\n description: options.description ?? null,\n fileKey: fileRecord.key,\n filename: options.filename,\n mimeType: options.mimeType,\n size: options.size,\n width,\n height,\n mediaType,\n })\n\n // 4. Get URL\n const url = await this.storage.getUrl(fileRecord.key)\n\n return {\n media: entityRecord,\n url,\n }\n } catch (error) {\n // Rollback: delete variants + original if entity creation fails\n\n // Delete variants first (best-effort)\n for (const vKey of Object.values(variantKeys)) {\n await this.storage.delete(vKey).catch(() => {})\n }\n\n // Delete original\n await this.storage.delete(fileRecord.key).catch(() => {\n // Storage rollback failure is already being handled — propagate original error\n })\n throw error\n }\n }\n\n // ---------------------------------------------------------------\n // CRUD delegation\n // ---------------------------------------------------------------\n\n async findById(id: string, options?: { locale?: string }): Promise<MediaRecord | null> {\n return this.admin.findById(id, options)\n }\n\n async findMany(options?: MediaListOptions): Promise<MediaListResult> {\n const { schemaRegistry } = await import('@murumets-ee/db')\n const { and, asc, desc, eq, ilike, or, sql } = await import('drizzle-orm')\n\n const table = schemaRegistry.get('media')\n if (!table) throw new Error('Media schema not registered. Is the media() plugin loaded?')\n\n // Build where conditions\n const conditions = []\n\n if (options?.mediaType) {\n conditions.push(eq(table.mediaType, options.mediaType))\n }\n if (options?.mimeTypePrefix) {\n // Escape ILIKE wildcards (%, _) in user input to prevent pattern injection\n const escaped = options.mimeTypePrefix.replace(/[\\\\%_]/g, '\\\\$&')\n conditions.push(ilike(table.mimeType, `${escaped}%`))\n }\n if (options?.search) {\n // Escape ILIKE wildcards in user input, then wrap with %...%\n const escaped = options.search.replace(/[\\\\%_]/g, '\\\\$&')\n const pattern = `%${escaped}%`\n conditions.push(\n or(\n ilike(table.filename, pattern),\n sql`${table.fields} ->> 'title' ILIKE ${pattern}`,\n )!,\n )\n }\n\n const limit = options?.limit ?? 50\n const offset = options?.offset ?? 0\n const whereClause = conditions.length > 0 ? and(...conditions) : undefined\n\n // Count total via AdminClient\n const total = await this.admin.count({ where: whereClause })\n\n // Fetch items via AdminClient for proper DTO shaping\n const orderField = options?.orderBy === 'filename' ? table.filename : table.createdAt\n const orderFn = (options?.orderDirection ?? 'desc') === 'asc' ? asc : desc\n\n const items = await this.admin.findMany({\n where: whereClause,\n limit,\n offset,\n orderBy: orderFn(orderField),\n })\n\n return {\n items,\n total,\n limit,\n offset,\n }\n }\n\n async update(\n id: string,\n data: { title?: string; alt?: string; description?: string },\n ): Promise<MediaRecord> {\n return this.admin.update(id, data)\n }\n\n /**\n * Delete a media entity, its variants, and its original file in storage.\n */\n async delete(id: string): Promise<void> {\n const record = await this.admin.findById(id)\n if (!record) throw new Error(`Media not found: ${id}`)\n\n const fileKey = record.fileKey\n\n // 1. Delete entity first (ref checking via entity_refs happens here)\n await this.admin.delete(id)\n\n // 2. Look up original file record for variant metadata\n const fileRecord = await this.storage.getMetadata(fileKey)\n const variants = (fileRecord?.metadata as Record<string, unknown> | null)?.variants as\n | Record<string, string>\n | undefined\n\n // 3. Delete variants (best-effort)\n if (variants) {\n for (const vKey of Object.values(variants)) {\n await this.storage.delete(vKey).catch(() => {\n // Variant deletion failure is non-fatal\n })\n }\n }\n\n // 4. Delete original file (best-effort)\n await this.storage.delete(fileKey).catch(() => {\n // Storage deletion failure is non-fatal — entity is already deleted\n })\n }\n\n // ---------------------------------------------------------------\n // URL resolution\n // ---------------------------------------------------------------\n\n /**\n * Get URL for a media entity by its ID.\n * Resolves entity -> fileKey -> storage URL.\n */\n async getUrl(id: string): Promise<string> {\n const record = await this.admin.findById(id)\n if (!record) throw new Error(`Media not found: ${id}`)\n\n return this.storage.getUrl(record.fileKey)\n }\n\n /**\n * Get URLs for multiple media entities (batch).\n * Returns a Map of mediaId -> url.\n */\n async getUrls(ids: string[]): Promise<Map<string, string>> {\n if (ids.length === 0) return new Map()\n\n const { schemaRegistry } = await import('@murumets-ee/db')\n const { inArray } = await import('drizzle-orm')\n\n const table = schemaRegistry.get('media')\n if (!table) return new Map()\n\n const records = await this.admin.findMany({\n where: inArray(table.id, ids),\n limit: ids.length,\n })\n\n const urlMap = new Map<string, string>()\n\n await Promise.all(\n records.map(async (record) => {\n const url = await this.storage.getUrl(record.fileKey)\n urlMap.set(record.id, url)\n }),\n )\n\n return urlMap\n }\n\n /**\n * Get variant URL for a specific image style.\n * Falls back to original URL if the variant doesn't exist.\n *\n * @param id - Media entity ID\n * @param styleName - Image style name (e.g., 'thumbnail')\n * @returns The variant URL, or original URL as fallback, or null if media not found\n */\n async getVariantUrl(id: string, styleName: string): Promise<string | null> {\n const record = await this.admin.findById(id)\n if (!record) return null\n\n const fileKey = record.fileKey\n\n // Try variant key first\n const styles = await this.resolveImageStyles()\n const style = styles[styleName]\n if (style) {\n const vKey = deriveVariantKey(fileKey, styleName, style.format ?? 'webp')\n try {\n return await this.storage.getUrl(vKey)\n } catch {\n // Variant doesn't exist — fall back to original\n }\n }\n\n // Fallback to original\n try {\n return await this.storage.getUrl(fileKey)\n } catch {\n return null\n }\n }\n\n /**\n * Get variant URLs for multiple media entities (batch).\n * Falls back to original URL per item if the variant doesn't exist.\n *\n * @param ids - Media entity IDs\n * @param styleName - Image style name (e.g., 'thumbnail')\n * @returns Map of mediaId -> variant URL (or original URL as fallback)\n */\n async getVariantUrls(ids: string[], styleName: string): Promise<Map<string, string>> {\n if (ids.length === 0) return new Map()\n\n const { schemaRegistry } = await import('@murumets-ee/db')\n const { inArray } = await import('drizzle-orm')\n\n const table = schemaRegistry.get('media')\n if (!table) return new Map()\n\n const records = await this.admin.findMany({\n where: inArray(table.id, ids),\n limit: ids.length,\n })\n\n const styles = await this.resolveImageStyles()\n const style = styles[styleName]\n const urlMap = new Map<string, string>()\n\n await Promise.all(\n records.map(async (record) => {\n // Try variant URL\n if (style) {\n const vKey = deriveVariantKey(record.fileKey, styleName, style.format ?? 'webp')\n try {\n const url = await this.storage.getUrl(vKey)\n urlMap.set(record.id, url)\n return\n } catch {\n // Variant doesn't exist — fall back to original\n }\n }\n\n // Fallback to original\n try {\n const url = await this.storage.getUrl(record.fileKey)\n urlMap.set(record.id, url)\n } catch {\n // Skip — no URL available\n }\n }),\n )\n\n return urlMap\n }\n}\n\n// ---------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------\n\nfunction deriveMediaType(mimeType: string): MediaType {\n if (mimeType.startsWith('image/')) return 'image'\n if (mimeType.startsWith('video/')) return 'video'\n if (mimeType.startsWith('audio/')) return 'audio'\n if (\n mimeType === 'application/pdf' ||\n mimeType.startsWith('application/msword') ||\n mimeType.startsWith('application/vnd.')\n ) {\n return 'document'\n }\n return 'other'\n}\n\nfunction deriveTitle(filename: string): string {\n const withoutExt = filename.replace(/\\.[^.]+$/, '')\n return withoutExt.replace(/[-_]/g, ' ')\n}\n\n/**\n * Factory — creates a MediaClient with an explicit StorageClient.\n * Must be called after createApp().\n */\nexport async function createMediaClient(storage: StorageClient): Promise<MediaClient> {\n const { createAdminClient } = await import('@murumets-ee/core/clients')\n const admin = createAdminClient(Media)\n return new MediaClient({ admin, storage })\n}\n\n// ---------------------------------------------------------------------------\n// Per-request MediaClient factory\n// ---------------------------------------------------------------------------\n//\n// NOTE: Storage config is process-global and safe to cache.\n// MediaClient / AdminClient must be built per-request — they carry a\n// context resolver tied to the calling request's user + permissions.\n// A singleton would leak one request's security context across others.\n\n/**\n * The storage singleton, which does NOT pin a failed initialisation.\n *\n * `_storagePromise ??= (...)()` used to cache the rejected promise too, so a\n * transient failure during storage init (config not yet loaded, a DB blip)\n * broke every subsequent caller until the process restarted. That mattered\n * little while this served admin operations; `plan/api` PR 5 puts it on the\n * ANONYMOUS request path via `getSharedStorageClient`, where the symptom\n * becomes every image on the site failing permanently with no recovery short of\n * a redeploy. See `cacheOnceUnlessRejected`, which is unit-tested.\n */\nconst _storageOnce = cacheOnceUnlessRejected<StorageClient>(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/**\n * The process-wide `StorageClient`, built once from the storage plugin config.\n *\n * Exported so the PUBLIC media resolver (`./public-resolver.ts`) reaches the\n * same instance rather than constructing a second one from a copy of these two\n * lines. Safe to share, and unlike `MediaClient`/`AdminClient` it MUST NOT be\n * rebuilt per request: it carries no security context — the read-side gate\n * lives in whichever client resolves the media rows, not here.\n */\nexport async function getSharedStorageClient(): Promise<StorageClient> {\n return getStorageSingleton()\n}\n\nasync function getStorageSingleton(): Promise<StorageClient> {\n return _storageOnce()\n}\n\n/**\n * Returns a fresh MediaClient wired to the current request's context.\n * Must be called after createApp(), inside a request context\n * (withAdminContext, runAsCli, etc.).\n *\n * Despite the name, this is NOT cached — the storage config is cached\n * internally but the MediaClient and its AdminClient are rebuilt per call\n * so the security context resolver attaches to the correct request.\n */\nexport async function getMediaClient(): Promise<MediaClient> {\n const { createAdminClient } = await import('@murumets-ee/core/clients')\n const storage = await getStorageSingleton()\n const admin = createAdminClient(Media)\n return new MediaClient({ admin, storage })\n}\n"],"mappings":"qMAoCA,IAAa,EAAb,KAAyB,CACvB,MACA,QACA,YAEA,YAAY,EAA2B,CACrC,KAAK,MAAQ,EAAO,MACpB,KAAK,QAAU,EAAO,QACtB,KAAK,YAAc,EAAO,aAAe,IAC3C,CAOA,MAAc,oBAA0D,CACtE,GAAI,KAAK,YAAa,OAAO,KAAK,YAClC,GAAM,CAAE,UAAW,MAAM,OAAO,qBAC1B,CAAE,sBAAuB,MAAM,OAAO,uCACtC,EAAM,EAAO,EAEnB,MADA,MAAK,YAAc,MAAM,EAAmB,EAAK,EAAI,MAAM,EACpD,KAAK,WACd,CAGA,4BAAmC,CACjC,KAAK,YAAc,IACrB,CAgBA,MAAM,OACJ,EACA,EAC4B,CAE5B,IAAM,EAAa,MAAM,KAAK,QAAQ,OAAO,EAAM,CACjD,SAAU,EAAQ,SAClB,SAAU,EAAQ,SAClB,KAAM,EAAQ,KACd,WAAY,EAAQ,WACpB,WAAY,EAAQ,UACtB,CAAC,EAGG,EAAQ,EAAQ,OAAS,KACzB,EAAS,EAAQ,QAAU,KACzB,EAAsC,CAAC,EAE7C,GAAI,aAAgB,QAAU,EAAmB,EAAQ,QAAQ,EAC/D,GAAI,CAEF,IAAM,EAAY,MAAM,EAAa,EAAM,MADtB,KAAK,mBAAmB,CACI,EAGjD,EAAQ,EAAU,MAClB,EAAS,EAAU,OAG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,EAAS,WAAW,QAAQ,EAAU,QAExC,IAAa,mBACb,EAAS,WAAW,oBAAoB,GACxC,EAAS,WAAW,kBAAkB,EAE/B,WAEF,OACT,CAEA,SAAS,EAAY,EAA0B,CAE7C,OADmB,EAAS,QAAQ,WAAY,EAChC,CAAC,CAAC,QAAQ,QAAS,GAAG,CACxC,CAMA,eAAsB,EAAkB,EAA8C,CACpF,GAAM,CAAE,qBAAsB,MAAM,OAAO,6BAE3C,OAAO,IAAI,EAAY,CAAE,MADX,EAAkB,CACH,EAAG,SAAQ,CAAC,CAC3C,CAsBA,MAAM,EAAe,EAAuC,SAAY,CACtE,GAAM,CAAE,UAAW,MAAM,OAAO,qBAC1B,CAAE,uBAAwB,MAAM,OAAO,wBACvC,CAAE,oBAAqB,MAAM,OAAO,+BACpC,EAAM,EAAO,EACnB,OAAO,EAAoB,EAAiB,EAAG,CAAE,KAAI,CAAC,CACxD,CAAC,EAWD,eAAsB,GAAiD,CACrE,OAAO,EAAoB,CAC7B,CAEA,eAAe,GAA8C,CAC3D,OAAO,EAAa,CACtB,CAWA,eAAsB,GAAuC,CAC3D,GAAM,CAAE,qBAAsB,MAAM,OAAO,6BACrC,EAAU,MAAM,EAAoB,EAE1C,OAAO,IAAI,EAAY,CAAE,MADX,EAAkB,CACH,EAAG,SAAQ,CAAC,CAC3C"}
1
+ {"version":3,"file":"client.mjs","names":[],"sources":["../src/derive-media-type.ts","../src/client.ts"],"sourcesContent":["import type { MediaType } from './types.js'\n\n/**\n * Classify a MIME type into the coarse `MediaType` an upload is stored under.\n *\n * Pure and dependency-free, and in its own module on purpose: `client.ts`\n * (`import 'server-only'`) needs it to set `mediaType` at upload, and the admin\n * list's MIME-type cell (`picker/media-type-icon.ts`, a CLIENT entry) needs the\n * same answer to pick an icon. One rule in one file means the icon a row shows\n * cannot disagree with the type it was stored as — which two copies would, the\n * first time someone taught one of them about a new document type.\n */\nexport function deriveMediaType(mimeType: string): MediaType {\n if (mimeType.startsWith('image/')) return 'image'\n if (mimeType.startsWith('video/')) return 'video'\n if (mimeType.startsWith('audio/')) return 'audio'\n if (\n mimeType === 'application/pdf' ||\n mimeType.startsWith('application/msword') ||\n mimeType.startsWith('application/vnd.')\n ) {\n return 'document'\n }\n return 'other'\n}\n","/**\n * MediaClient — wraps AdminClient + StorageClient for media management.\n *\n * Usage:\n * import { createMediaClient } from '@murumets-ee/media/client'\n * const media = await createMediaClient(storageClient)\n * const result = await media.upload(buffer, { filename: 'photo.jpg', mimeType: 'image/jpeg', size: 12345 })\n */\n\nimport 'server-only'\n\nimport type { AdminClient } from '@murumets-ee/entity/admin'\nimport type { StorageClient } from '@murumets-ee/storage'\nimport { cacheOnceUnlessRejected } from './async-cache.js'\nimport type { FocalPoint } from './crop/focal-point.js'\nimport { deriveMediaType } from './derive-media-type.js'\nimport { Media } from './entity.js'\nimport { detectFocalPoint, isProcessableImage, processImage } from './process-image.js'\nimport type {\n ImageStyle,\n MediaListOptions,\n MediaListResult,\n MediaRecord,\n MediaUploadOptions,\n MediaUploadResult,\n} from './types.js'\nimport { deriveVariantKey } from './variant-key.js'\n\ntype MediaFields = typeof Media.allFields\n\nexport interface MediaClientConfig {\n admin: AdminClient<MediaFields>\n storage: StorageClient\n /** Image styles to generate on upload. Loaded from plugin config if not provided. */\n imageStyles?: Record<string, ImageStyle>\n}\n\nexport class MediaClient {\n private admin: AdminClient<MediaFields>\n private storage: StorageClient\n private imageStyles: Record<string, ImageStyle> | null\n\n constructor(config: MediaClientConfig) {\n this.admin = config.admin\n this.storage = config.storage\n this.imageStyles = config.imageStyles ?? null\n }\n\n /**\n * Resolve image styles via the shared waterfall (settings DB → plugin\n * config → hardcoded defaults) and cache the result on this instance.\n * Call `invalidateImageStylesCache()` after a settings update.\n */\n private async resolveImageStyles(): Promise<Record<string, ImageStyle>> {\n if (this.imageStyles) return this.imageStyles\n const { getApp } = await import('@murumets-ee/core')\n const { resolveImageStyles } = await import('./resolve-image-styles.js')\n const app = getApp()\n this.imageStyles = await resolveImageStyles(app, app.logger)\n return this.imageStyles\n }\n\n /** Clear cached styles so next access re-reads from settings DB. */\n invalidateImageStylesCache(): void {\n this.imageStyles = null\n }\n\n // ---------------------------------------------------------------\n // Upload — the key convenience method\n // ---------------------------------------------------------------\n\n /**\n * Upload a file and create a media entity record in one step.\n * 1. Uploads original to storage (StorageClient)\n * 2. If image: extracts dimensions via Sharp + generates variants\n * 3. Creates media entity record (AdminClient)\n * 4. Returns the media record + URL\n *\n * Rolls back storage upload if entity creation fails.\n * Variant generation failures are logged but don't fail the upload.\n */\n async upload(\n data: Buffer | ReadableStream<Uint8Array>,\n options: MediaUploadOptions,\n ): Promise<MediaUploadResult> {\n // 1. Upload original file to storage\n const fileRecord = await this.storage.upload(data, {\n filename: options.filename,\n mimeType: options.mimeType,\n size: options.size,\n visibility: options.visibility,\n uploadedBy: options.uploadedBy,\n })\n\n // 2. Image processing — extract dimensions + generate variants\n let width = options.width ?? null\n let height = options.height ?? null\n // `null` renders as the centre (images D010), so a failed or skipped guess\n // is exactly today's crop rather than an error.\n let focalPoint: FocalPoint | null = null\n const variantKeys: Record<string, string> = {}\n\n if (data instanceof Buffer && isProcessableImage(options.mimeType)) {\n try {\n const styles = await this.resolveImageStyles()\n // The focal-point seed runs beside the variants rather than after them —\n // two independent sharp passes over the same buffer. Its own failure is\n // swallowed here so a photograph the attention pass cannot read still\n // gets its variants.\n const [processed, seeded] = await Promise.all([\n processImage(data, styles),\n detectFocalPoint(data).catch(async (err: unknown) => {\n await warnFocalPointFailed(err, options.filename)\n return null\n }),\n ])\n focalPoint = seeded\n\n // Set dimensions from Sharp metadata\n width = processed.width\n height = processed.height\n\n // Upload each variant to storage\n const visibility = fileRecord.visibility\n await Promise.all(\n [...processed.variants.entries()].map(async ([styleName, variant]) => {\n const vKey = deriveVariantKey(fileRecord.key, styleName, variant.format)\n try {\n await this.storage.upload(variant.buffer, {\n key: vKey,\n filename: `${styleName}_${options.filename}`,\n mimeType: variant.mimeType,\n size: variant.buffer.byteLength,\n visibility,\n metadata: { variantOf: fileRecord.key, style: styleName },\n uploadedBy: options.uploadedBy,\n })\n variantKeys[styleName] = vKey\n } catch {\n // Variant upload failure is non-fatal — original is saved\n }\n }),\n )\n\n // Store variant keys in original file's metadata\n if (Object.keys(variantKeys).length > 0) {\n await this.storage\n .updateMetadata(fileRecord.key, {\n metadata: {\n ...(fileRecord.metadata ?? {}),\n variants: variantKeys,\n },\n })\n .catch(() => {\n // Metadata update failure is non-fatal\n })\n }\n } catch {\n // Image processing failure is non-fatal — original is saved\n }\n }\n\n // 3. Create media entity record\n const mediaType = deriveMediaType(options.mimeType)\n\n try {\n const entityRecord = await this.admin.create({\n title: options.title ?? deriveTitle(options.filename),\n alt: options.alt ?? null,\n description: options.description ?? null,\n fileKey: fileRecord.key,\n filename: options.filename,\n mimeType: options.mimeType,\n size: options.size,\n width,\n height,\n focalPoint,\n mediaType,\n })\n\n // 4. Get URL\n const url = await this.storage.getUrl(fileRecord.key)\n\n return {\n media: entityRecord,\n url,\n }\n } catch (error) {\n // Rollback: delete variants + original if entity creation fails\n\n // Delete variants first (best-effort)\n for (const vKey of Object.values(variantKeys)) {\n await this.storage.delete(vKey).catch(() => {})\n }\n\n // Delete original\n await this.storage.delete(fileRecord.key).catch(() => {\n // Storage rollback failure is already being handled — propagate original error\n })\n throw error\n }\n }\n\n // ---------------------------------------------------------------\n // CRUD delegation\n // ---------------------------------------------------------------\n\n async findById(id: string, options?: { locale?: string }): Promise<MediaRecord | null> {\n return this.admin.findById(id, options)\n }\n\n async findMany(options?: MediaListOptions): Promise<MediaListResult> {\n const { schemaRegistry } = await import('@murumets-ee/db')\n const { and, asc, desc, eq, ilike, or, sql } = await import('drizzle-orm')\n\n const table = schemaRegistry.get('media')\n if (!table) throw new Error('Media schema not registered. Is the media() plugin loaded?')\n\n // Build where conditions\n const conditions = []\n\n if (options?.mediaType) {\n conditions.push(eq(table.mediaType, options.mediaType))\n }\n if (options?.mimeTypePrefix) {\n // Escape ILIKE wildcards (%, _) in user input to prevent pattern injection\n const escaped = options.mimeTypePrefix.replace(/[\\\\%_]/g, '\\\\$&')\n conditions.push(ilike(table.mimeType, `${escaped}%`))\n }\n if (options?.search) {\n // Escape ILIKE wildcards in user input, then wrap with %...%\n const escaped = options.search.replace(/[\\\\%_]/g, '\\\\$&')\n const pattern = `%${escaped}%`\n conditions.push(\n or(\n ilike(table.filename, pattern),\n sql`${table.fields} ->> 'title' ILIKE ${pattern}`,\n )!,\n )\n }\n\n const limit = options?.limit ?? 50\n const offset = options?.offset ?? 0\n const whereClause = conditions.length > 0 ? and(...conditions) : undefined\n\n // Count total via AdminClient\n const total = await this.admin.count({ where: whereClause })\n\n // Fetch items via AdminClient for proper DTO shaping\n const orderField = options?.orderBy === 'filename' ? table.filename : table.createdAt\n const orderFn = (options?.orderDirection ?? 'desc') === 'asc' ? asc : desc\n\n const items = await this.admin.findMany({\n where: whereClause,\n limit,\n offset,\n orderBy: orderFn(orderField),\n })\n\n return {\n items,\n total,\n limit,\n offset,\n }\n }\n\n async update(\n id: string,\n data: { title?: string; alt?: string; description?: string },\n ): Promise<MediaRecord> {\n return this.admin.update(id, data)\n }\n\n /**\n * Delete a media entity, its variants, and its original file in storage.\n */\n async delete(id: string): Promise<void> {\n const record = await this.admin.findById(id)\n if (!record) throw new Error(`Media not found: ${id}`)\n\n const fileKey = record.fileKey\n\n // 1. Delete entity first (ref checking via entity_refs happens here)\n await this.admin.delete(id)\n\n // 2. Look up original file record for variant metadata\n const fileRecord = await this.storage.getMetadata(fileKey)\n const variants = (fileRecord?.metadata as Record<string, unknown> | null)?.variants as\n | Record<string, string>\n | undefined\n\n // 3. Delete variants (best-effort)\n if (variants) {\n for (const vKey of Object.values(variants)) {\n await this.storage.delete(vKey).catch(() => {\n // Variant deletion failure is non-fatal\n })\n }\n }\n\n // 4. Delete original file (best-effort)\n await this.storage.delete(fileKey).catch(() => {\n // Storage deletion failure is non-fatal — entity is already deleted\n })\n }\n\n // ---------------------------------------------------------------\n // URL resolution\n // ---------------------------------------------------------------\n\n /**\n * Get URL for a media entity by its ID.\n * Resolves entity -> fileKey -> storage URL.\n */\n async getUrl(id: string): Promise<string> {\n const record = await this.admin.findById(id)\n if (!record) throw new Error(`Media not found: ${id}`)\n\n return this.storage.getUrl(record.fileKey)\n }\n\n /**\n * Get URLs for multiple media entities (batch).\n * Returns a Map of mediaId -> url.\n */\n async getUrls(ids: string[]): Promise<Map<string, string>> {\n if (ids.length === 0) return new Map()\n\n const { schemaRegistry } = await import('@murumets-ee/db')\n const { inArray } = await import('drizzle-orm')\n\n const table = schemaRegistry.get('media')\n if (!table) return new Map()\n\n const records = await this.admin.findMany({\n where: inArray(table.id, ids),\n limit: ids.length,\n })\n\n const urlMap = new Map<string, string>()\n\n await Promise.all(\n records.map(async (record) => {\n const url = await this.storage.getUrl(record.fileKey)\n urlMap.set(record.id, url)\n }),\n )\n\n return urlMap\n }\n\n /**\n * Get variant URL for a specific image style.\n * Falls back to original URL if the variant doesn't exist.\n *\n * @param id - Media entity ID\n * @param styleName - Image style name (e.g., 'thumbnail')\n * @returns The variant URL, or original URL as fallback, or null if media not found\n */\n async getVariantUrl(id: string, styleName: string): Promise<string | null> {\n const record = await this.admin.findById(id)\n if (!record) return null\n\n const fileKey = record.fileKey\n\n // Try variant key first\n const styles = await this.resolveImageStyles()\n const style = styles[styleName]\n if (style) {\n const vKey = deriveVariantKey(fileKey, styleName, style.format ?? 'webp')\n try {\n return await this.storage.getUrl(vKey)\n } catch {\n // Variant doesn't exist — fall back to original\n }\n }\n\n // Fallback to original\n try {\n return await this.storage.getUrl(fileKey)\n } catch {\n return null\n }\n }\n\n /**\n * Get variant URLs for multiple media entities (batch).\n * Falls back to original URL per item if the variant doesn't exist.\n *\n * @param ids - Media entity IDs\n * @param styleName - Image style name (e.g., 'thumbnail')\n * @returns Map of mediaId -> variant URL (or original URL as fallback)\n */\n async getVariantUrls(ids: string[], styleName: string): Promise<Map<string, string>> {\n if (ids.length === 0) return new Map()\n\n const { schemaRegistry } = await import('@murumets-ee/db')\n const { inArray } = await import('drizzle-orm')\n\n const table = schemaRegistry.get('media')\n if (!table) return new Map()\n\n const records = await this.admin.findMany({\n where: inArray(table.id, ids),\n limit: ids.length,\n })\n\n const styles = await this.resolveImageStyles()\n const style = styles[styleName]\n const urlMap = new Map<string, string>()\n\n await Promise.all(\n records.map(async (record) => {\n // Try variant URL\n if (style) {\n const vKey = deriveVariantKey(record.fileKey, styleName, style.format ?? 'webp')\n try {\n const url = await this.storage.getUrl(vKey)\n urlMap.set(record.id, url)\n return\n } catch {\n // Variant doesn't exist — fall back to original\n }\n }\n\n // Fallback to original\n try {\n const url = await this.storage.getUrl(record.fileKey)\n urlMap.set(record.id, url)\n } catch {\n // Skip — no URL available\n }\n }),\n )\n\n return urlMap\n }\n}\n\n// ---------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------\n\nfunction deriveTitle(filename: string): string {\n const withoutExt = filename.replace(/\\.[^.]+$/, '')\n return withoutExt.replace(/[-_]/g, ' ')\n}\n\n/**\n * Factory — creates a MediaClient with an explicit StorageClient.\n * Must be called after createApp().\n */\nexport async function createMediaClient(storage: StorageClient): Promise<MediaClient> {\n const { createAdminClient } = await import('@murumets-ee/core/clients')\n const admin = createAdminClient(Media)\n return new MediaClient({ admin, storage })\n}\n\n// ---------------------------------------------------------------------------\n// Per-request MediaClient factory\n// ---------------------------------------------------------------------------\n//\n// NOTE: Storage config is process-global and safe to cache.\n// MediaClient / AdminClient must be built per-request — they carry a\n// context resolver tied to the calling request's user + permissions.\n// A singleton would leak one request's security context across others.\n\n/**\n * The storage singleton, which does NOT pin a failed initialisation.\n *\n * `_storagePromise ??= (...)()` used to cache the rejected promise too, so a\n * transient failure during storage init (config not yet loaded, a DB blip)\n * broke every subsequent caller until the process restarted. That mattered\n * little while this served admin operations; `plan/api` PR 5 puts it on the\n * ANONYMOUS request path via `getSharedStorageClient`, where the symptom\n * becomes every image on the site failing permanently with no recovery short of\n * a redeploy. See `cacheOnceUnlessRejected`, which is unit-tested.\n */\nconst _storageOnce = cacheOnceUnlessRejected<StorageClient>(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/**\n * The process-wide `StorageClient`, built once from the storage plugin config.\n *\n * Exported so the PUBLIC media resolver (`./public-resolver.ts`) reaches the\n * same instance rather than constructing a second one from a copy of these two\n * lines. Safe to share, and unlike `MediaClient`/`AdminClient` it MUST NOT be\n * rebuilt per request: it carries no security context — the read-side gate\n * lives in whichever client resolves the media rows, not here.\n */\nexport async function getSharedStorageClient(): Promise<StorageClient> {\n return getStorageSingleton()\n}\n\nasync function getStorageSingleton(): Promise<StorageClient> {\n return _storageOnce()\n}\n\n/**\n * Returns a fresh MediaClient wired to the current request's context.\n * Must be called after createApp(), inside a request context\n * (withAdminContext, runAsCli, etc.).\n *\n * Despite the name, this is NOT cached — the storage config is cached\n * internally but the MediaClient and its AdminClient are rebuilt per call\n * so the security context resolver attaches to the correct request.\n */\nexport async function getMediaClient(): Promise<MediaClient> {\n const { createAdminClient } = await import('@murumets-ee/core/clients')\n const storage = await getStorageSingleton()\n const admin = createAdminClient(Media)\n return new MediaClient({ admin, storage })\n}\n\n/**\n * A failed focal-point guess is not an upload failure — the row is stored with\n * `null`, which renders as the centre (D010) — but it is not silent either: a\n * decoder that cannot read a whole format would otherwise leave every such\n * photograph centred with nothing saying why.\n */\nasync function warnFocalPointFailed(err: unknown, filename: string): Promise<void> {\n try {\n const { getApp } = await import('@murumets-ee/core')\n getApp().logger.warn({ err, filename }, 'media: focal-point detection failed; stored as centre')\n } catch (loggerErr) {\n // No app (a script, a test) — fall back to the console rather than lose it.\n console.warn('media: focal-point detection failed; stored as centre', filename, err, loggerErr)\n }\n}\n"],"mappings":"iNAYA,SAAgB,EAAgB,EAA6B,CAW3D,OAVI,EAAS,WAAW,QA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6BAE3C,OAAO,IAAI,EAAY,CAAE,MADX,EAAkB,CACH,EAAG,SAAQ,CAAC,CAC3C,CAsBA,MAAM,EAAe,EAAuC,SAAY,CACtE,GAAM,CAAE,UAAW,MAAM,OAAO,qBAC1B,CAAE,uBAAwB,MAAM,OAAO,wBACvC,CAAE,oBAAqB,MAAM,OAAO,+BACpC,EAAM,EAAO,EACnB,OAAO,EAAoB,EAAiB,EAAG,CAAE,KAAI,CAAC,CACxD,CAAC,EAWD,eAAsB,GAAiD,CACrE,OAAO,EAAoB,CAC7B,CAEA,eAAe,GAA8C,CAC3D,OAAO,EAAa,CACtB,CAWA,eAAsB,GAAuC,CAC3D,GAAM,CAAE,qBAAsB,MAAM,OAAO,6BACrC,EAAU,MAAM,EAAoB,EAE1C,OAAO,IAAI,EAAY,CAAE,MADX,EAAkB,CACH,EAAG,SAAQ,CAAC,CAC3C,CAQA,eAAe,EAAqB,EAAc,EAAiC,CACjF,GAAI,CACF,GAAM,CAAE,UAAW,MAAM,OAAO,qBAChC,EAAO,CAAC,CAAC,OAAO,KAAK,CAAE,MAAK,UAAS,EAAG,uDAAuD,CACjG,OAAS,EAAW,CAElB,QAAQ,KAAK,wDAAyD,EAAU,EAAK,CAAS,CAChG,CACF"}
@@ -0,0 +1,2 @@
1
+ import { a as formatObjectPosition, c as objectPositionFor, i as focalCropRect, l as readFocalPoint, n as FocalPoint, o as isCentreFocalPoint, r as FractionalRect, s as isFocalPoint, t as CENTRE_FOCAL_POINT, u as visibleWindow } from "./focal-point-C_0drV03.mjs";
2
+ export { CENTRE_FOCAL_POINT, type FocalPoint, type FractionalRect, focalCropRect, formatObjectPosition, isCentreFocalPoint, isFocalPoint, objectPositionFor, readFocalPoint, visibleWindow };
package/dist/crop.mjs ADDED
@@ -0,0 +1 @@
1
+ import{a as e,c as t,i as n,n as r,o as i,r as a,s as o,t as s}from"./focal-point-BWhtJzef.mjs";export{s as CENTRE_FOCAL_POINT,r as focalCropRect,a as formatObjectPosition,n as isCentreFocalPoint,e as isFocalPoint,i as objectPositionFor,o as readFocalPoint,t as visibleWindow};
@@ -0,0 +1,2 @@
1
+ import{behavior as e,defineEntity as t,field as n,searchable as r}from"@murumets-ee/entity";import{z as i}from"zod";Object.freeze({x:.5,y:.5});function a(e){return typeof e==`number`&&Number.isFinite(e)&&e>=0&&e<=1}function o(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.keys(e);if(t.length!==2||!t.includes(`x`)||!t.includes(`y`))return!1;let{x:n,y:r}=e;return a(n)&&a(r)}function s(e){if(!(`focalPoint`in e))return e;let t=e.focalPoint;if(t==null||o(t))return e;throw new i.ZodError([{code:`custom`,path:[`focalPoint`],message:`focalPoint must be { x, y } with both between 0 and 1, or null.`}])}function c(e){if(e.keys.includes(`focalPoint`))throw new i.ZodError([{code:`custom`,path:[`focalPoint`],message:`bulk update on '${e.entityName}' cannot write 'focalPoint': updateMany runs no per-row hooks, so the value would bypass its shape check. Update each row individually.`}])}function l(){return{name:`focalPointValidation`,hooks:{beforeCreate:async e=>s(e),beforeUpdate:async(e,t)=>s(t)},assertBulkUpdate:c}}const u=t({name:`media`,fields:{title:n.text({translatable:!0}),alt:n.text({translatable:!0}),description:n.text({translatable:!0}),fileKey:n.text({required:!0,indexed:!0}),filename:n.text({required:!0}),mimeType:n.text({required:!0,indexed:!0,admin:{display:{type:`mimeType`}}}),size:n.number({required:!0,integer:!0,admin:{display:{type:`filesize`}}}),width:n.number({integer:!0}),height:n.number({integer:!0}),focalPoint:n.json(),mediaType:n.select({options:[`image`,`video`,`audio`,`document`,`other`],required:!0,indexed:!0})},behaviors:[e.auditable(),l(),r({fields:[`filename`,`fileKey`,`mimeType`,`title`,`alt`,`description`],fts:{fields:[`filename`,`title`,`alt`,`description`],language:`simple`},projection:e=>({id:e.id,label:e.title??e.filename,description:e.mimeType})})],admin:{list:{fields:[`title`,`mimeType`,`size`,`createdAt`],layouts:[`table`,`grid`]}},scope:`global`,access:{view:`public`,create:`group.editor`,update:`group.editor`,delete:`group.admin`}});export{u as Media};
2
+ //# sourceMappingURL=entity-CNxAERYG.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"entity-CNxAERYG.mjs","names":[],"sources":["../src/crop/focal-point.ts","../src/crop/focal-point-validation.ts","../src/entity.ts"],"sourcesContent":["/**\n * The focal point, and every number derived from it — ONE pure module.\n *\n * A photograph's focal point is stored once, on the media row, as a fraction of\n * the image (`{x, y}` in `[0, 1]`, images D002). Two consumers turn it into a\n * crop: the browser, through `object-position` on a shaped slot (this PR), and\n * sharp, through `extract()` before a shaped variant is resized (images PR04).\n * Both import this file, so the generated crop and the CSS crop cannot\n * disagree — they are the same arithmetic, not two copies of it.\n *\n * No DOM, no sharp, no database. It is imported by `@murumets-ee/blocks`' render\n * spine, which ships to every visitor's browser, so it must stay small and must\n * never import anything.\n *\n * ## Fractions, never pixels\n *\n * A pixel rect breaks the moment the source file is replaced at a different\n * resolution, and this toolkit's stored `width`/`height` are client-measured and\n * can be wrong (images R003). A fraction survives both.\n *\n * ## Why `object-position` is NOT `focal × 100%`\n *\n * `object-position` is an ALIGNMENT percentage: `75%` puts the image's 75% point\n * at the BOX's 75% point, not at its centre (css-backgrounds-3, \"the point 75%\n * across … is to be placed at the point 75% across the area\"). The naive\n * `object-position: {f·100}%` is therefore wrong by `|f − 0.5| × box_width` —\n * exactly zero for a centred subject and 50% of the box at the edges, which is\n * why it survives review (R002). The conversion, per axis:\n *\n * ```\n * w_vis = C / I // visible window, as a fraction of the image\n * L = clamp(f − w_vis / 2, 0, 1 − w_vis) // the window's leading edge\n * P = L / (1 − w_vis) // the object-position fraction\n * ```\n *\n * `P` depends on the CONTAINER's ratio through `w_vis`, which is why it is\n * computed at render and never stored (D002 rules out storing it).\n *\n * ## Absent and centre are the same thing\n *\n * {@link readFocalPoint} turns every absent, malformed or out-of-range value into\n * `{0.5, 0.5}`, and the centre produces `object-position: 50% 50%`, which is\n * CSS's initial value. So a legacy row with no focal point and a row whose focal\n * point is the centre render identically, and nothing downstream branches on\n * the difference (D010).\n */\n\n/**\n * A point in the image, as fractions of its width and height. Both in `[0, 1]`.\n *\n * A `type`, not an `interface`, on purpose: it is stored in a `field.json()`\n * column, and only a type alias is assignable to the entity's `JsonValue`\n * (an interface has no implicit index signature).\n */\nexport type FocalPoint = {\n readonly x: number\n readonly y: number\n}\n\n/** A rectangle in the image, as fractions of its width and height. */\nexport type FractionalRect = {\n readonly x: number\n readonly y: number\n readonly w: number\n readonly h: number\n}\n\n/** The default — and what every absent or unusable focal point means. */\nexport const CENTRE_FOCAL_POINT: FocalPoint = Object.freeze({ x: 0.5, y: 0.5 })\n\nfunction isUnitFraction(value: unknown): value is number {\n return typeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= 1\n}\n\n/**\n * Is `value` a storable focal point — exactly `{x, y}`, both finite fractions?\n *\n * STRICT, because it guards a WRITE (the media row's `focalPoint` column). An\n * extra key is refused rather than stripped: a JSON column that stores what it\n * was sent would otherwise accept `{x, y, notes: '<a megabyte>'}` and hand it to\n * every reader of every page that draws the photograph.\n */\nexport function isFocalPoint(value: unknown): value is FocalPoint {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false\n const keys = Object.keys(value)\n if (keys.length !== 2 || !keys.includes('x') || !keys.includes('y')) return false\n const { x, y } = value as { x: unknown; y: unknown }\n return isUnitFraction(x) && isUnitFraction(y)\n}\n\n/**\n * The focal point to RENDER with, from whatever a projection carried.\n *\n * LENIENT, because it guards a READ: an absent, null or malformed value is the\n * centre, never a throw. A render that threw on a bad stored value would take\n * the whole page down over one photograph's crop.\n */\nexport function readFocalPoint(value: unknown): FocalPoint {\n return isFocalPoint(value) ? value : CENTRE_FOCAL_POINT\n}\n\n/** Is this the centre — the point that needs no `object-position` at all? */\nexport function isCentreFocalPoint(focal: FocalPoint): boolean {\n return focal.x === 0.5 && focal.y === 0.5\n}\n\nfunction clamp(value: number, min: number, max: number): number {\n return Math.min(Math.max(value, min), max)\n}\n\n/**\n * The window a `cover` crop leaves visible, as a fraction of the image on each\n * axis.\n *\n * Under `object-fit: cover` the image is scaled until it covers the box, so at\n * most ONE axis overflows and the other is exactly `1`. `imageRatio` and\n * `boxRatio` are width / height. A ratio that is not a positive finite number\n * is a caller bug; it is answered with \"nothing overflows\" (`{1, 1}`), which\n * renders as today's centre crop rather than as `NaN%`.\n */\nexport function visibleWindow(\n imageRatio: number,\n boxRatio: number,\n): { readonly w: number; readonly h: number } {\n if (!(imageRatio > 0 && Number.isFinite(imageRatio) && boxRatio > 0 && Number.isFinite(boxRatio)))\n return { w: 1, h: 1 }\n // Image wider than the box → the horizontal axis overflows.\n if (imageRatio > boxRatio) return { w: boxRatio / imageRatio, h: 1 }\n return { w: 1, h: imageRatio / boxRatio }\n}\n\n/**\n * One axis of the conversion: the window's leading edge `L`, clamped so the\n * window never leaves the image.\n *\n * Clamping `L` to `[0, 1 − w_vis]` is exactly equivalent to clamping the\n * resulting `object-position` to `[0, 1]`, so \"never reveal background\" has one\n * spelling here rather than two (R002).\n */\nfunction windowStart(focal: number, visible: number): number {\n return clamp(focal - visible / 2, 0, 1 - visible)\n}\n\n/**\n * The crop a focal point implies for a box of `boxRatio`, as a fractional rect\n * of the image — the region sharp will `extract()` (images PR04) and the region\n * the browser shows through {@link objectPositionFor}.\n */\nexport function focalCropRect(\n focal: FocalPoint,\n imageRatio: number,\n boxRatio: number,\n): FractionalRect {\n const visible = visibleWindow(imageRatio, boxRatio)\n return {\n x: windowStart(focal.x, visible.w),\n y: windowStart(focal.y, visible.h),\n w: visible.w,\n h: visible.h,\n }\n}\n\n/**\n * The `object-position` fractions that make a `cover`-fitted image show\n * {@link focalCropRect}'s window.\n *\n * An axis that does not overflow (`w_vis == 1`) has no position to choose —\n * `object-position` is inert on it — so it answers `0.5`, CSS's own default.\n * That keeps the centre case literally `{0.5, 0.5}` and the emitted CSS\n * byte-comparable with a slot that has no focal point.\n */\nexport function objectPositionFor(\n focal: FocalPoint,\n imageRatio: number,\n boxRatio: number,\n): FocalPoint {\n const rect = focalCropRect(focal, imageRatio, boxRatio)\n return {\n x: rect.w < 1 ? rect.x / (1 - rect.w) : 0.5,\n y: rect.h < 1 ? rect.y / (1 - rect.h) : 0.5,\n }\n}\n\n/**\n * Format a position as a CSS `object-position` value: two percentages, rounded\n * to two decimals so the emitted markup is stable across floating-point noise\n * (`33.33% 50%`, not `33.333333333333336% 50%`).\n */\nexport function formatObjectPosition(position: FocalPoint): string {\n return `${percent(position.x)} ${percent(position.y)}`\n}\n\nfunction percent(fraction: number): string {\n return `${Math.round(fraction * 10000) / 100}%`\n}\n","/**\n * `focalPointValidation()` — the write guard on `media.focalPoint`.\n *\n * `field.json()` validates as the permissive JSON union on purpose, so without\n * this hook an editor's PATCH could park any shape in the column — a megabyte\n * string, a nested object — and every public page drawing the photograph would\n * carry it, because the projection hands the value to the render. CLAUDE.md's\n * \"validate at the boundary\", on the one column this package adds.\n *\n * Errors are `ZodError`s, so the admin API answers 400 with an issue pathed at\n * `focalPoint` rather than a 500 — the contract `menuEntityTypesValidation()`\n * already relies on.\n */\n\nimport type { Behavior, BulkUpdateInfo } from '@murumets-ee/entity'\nimport { z } from 'zod'\nimport { isFocalPoint } from './focal-point.js'\n\n/**\n * `null` is a legitimate value — it means \"no focal point\", which renders as the\n * centre (D010). Anything else must be exactly `{x, y}` in `[0, 1]`.\n */\nfunction validateFocalPoint(data: Record<string, unknown>): Record<string, unknown> {\n // A payload without the key is a partial update that does not touch the\n // column. Defaulting it here would let a title-only PATCH reset the point.\n if (!('focalPoint' in data)) return data\n const value = data.focalPoint\n if (value === null || value === undefined || isFocalPoint(value)) return data\n throw new z.ZodError([\n {\n code: 'custom',\n path: ['focalPoint'],\n message: 'focalPoint must be { x, y } with both between 0 and 1, or null.',\n },\n ])\n}\n\n/**\n * `updateMany` runs no per-row hooks, so `beforeUpdate` never sees a bulk write.\n * Refused rather than validated: `BulkUpdateInfo` is deliberately shape-only (it\n * names the columns, never the values), and \"every photograph has the same\n * subject position\" is not an intent anyone has. A migration is the tool for a\n * one-off backfill.\n */\nfunction assertNoBulkFocalPointWrite(info: BulkUpdateInfo): void {\n if (!info.keys.includes('focalPoint')) return\n throw new z.ZodError([\n {\n code: 'custom',\n path: ['focalPoint'],\n message:\n `bulk update on '${info.entityName}' cannot write 'focalPoint': updateMany runs no ` +\n 'per-row hooks, so the value would bypass its shape check. Update each row individually.',\n },\n ])\n}\n\n/**\n * Contributes NO fields — the empty map `Record<never, never>`, not\n * `Record<string, never>`, which would merge into the entity's field map and\n * collapse every field to `never`.\n */\nexport function focalPointValidation(): Behavior<Record<never, never>, 'focalPointValidation'> {\n return {\n name: 'focalPointValidation',\n hooks: {\n beforeCreate: async (data) => validateFocalPoint(data),\n beforeUpdate: async (_id, data) => validateFocalPoint(data),\n },\n assertBulkUpdate: assertNoBulkFocalPointWrite,\n }\n}\n","/**\n * Pre-defined Media entity.\n *\n * Auto-registered by the media() plugin — users do NOT add this to their entities array.\n * Connected to toolkit_files via the fileKey field (stores the StorageClient file key).\n *\n * @example\n * ```typescript\n * import { media } from '@murumets-ee/media/plugin'\n *\n * export default defineConfig({\n * plugins: [storage(), media()],\n * // Media entity is auto-added — no need to list it here\n * })\n * ```\n */\n\nimport { behavior, defineEntity, field, searchable } from '@murumets-ee/entity'\nimport { focalPointValidation } from './crop/focal-point-validation.js'\n\nexport const Media = defineEntity({\n name: 'media',\n fields: {\n // --- Display metadata (editable, translatable) ---\n title: field.text({ translatable: true }),\n alt: field.text({ translatable: true }),\n description: field.text({ translatable: true }),\n\n // --- File linkage (set on upload, immutable in practice) ---\n /** Key into toolkit_files table (e.g., 'uploads/2026/02/uuid/photo.jpg') */\n fileKey: field.text({ required: true, indexed: true }),\n\n // --- File metadata (set on upload) ---\n filename: field.text({ required: true }),\n // Drawn as an icon in the admin list (a film for `video/mp4`), not the raw\n // string — declared on the field, so any list of media reads the same\n // (entity-table D008).\n mimeType: field.text({\n required: true,\n indexed: true,\n admin: { display: { type: 'mimeType' } },\n }),\n // Bytes, drawn as \"1.5 MB\" in the operator's locale in the admin list\n // (entity-table D008). Hidden by default — an unindexed number is — and one\n // click away in the View menu.\n size: field.number({\n required: true,\n integer: true,\n admin: { display: { type: 'filesize' } },\n }),\n\n // --- Image-specific metadata (client-measured on upload) ---\n width: field.number({ integer: true }),\n height: field.number({ integer: true }),\n /**\n * Where the subject is, as `{ x, y }` fractions of the image — never pixels,\n * so it survives the file being replaced at another resolution (images\n * D002). A shaped slot crops around it (`@murumets-ee/media/crop`).\n *\n * Nullable, and `null` means the centre: an absent point and `{0.5, 0.5}`\n * render identically, so no reader branches on a legacy row (D010). The\n * shape is enforced by `focalPointValidation()` below — `field.json()` on\n * its own accepts any JSON.\n */\n focalPoint: field.json(),\n\n // --- Classification (derived from mimeType on upload) ---\n mediaType: field.select({\n options: ['image', 'video', 'audio', 'document', 'other'] as const,\n required: true,\n indexed: true,\n }),\n },\n behaviors: [\n behavior.auditable(),\n focalPointValidation(),\n // filename / fileKey / mimeType live on the main table.\n // title/alt/description are translatable — their tsvector goes on\n // media_translations so non-default-locale callers still get FTS.\n searchable({\n fields: ['filename', 'fileKey', 'mimeType', 'title', 'alt', 'description'],\n fts: {\n fields: ['filename', 'title', 'alt', 'description'],\n language: 'simple',\n },\n projection: (row) => ({\n id: row.id as string,\n label: (row.title as string | undefined) ?? (row.filename as string),\n description: row.mimeType as string,\n }),\n }),\n ],\n admin: {\n list: {\n // Title first (its own row-link column), then the type — the icon\n // display already draws it, so the raw `mimeType` string is not a\n // second column — size and when it was added. `fileKey` (the raw\n // storage path) and `mediaType` (redundant with the icon) stay off by\n // default, one View-menu click away (entity-table PR06 §6).\n fields: ['title', 'mimeType', 'size', 'createdAt'],\n layouts: ['table', 'grid'],\n },\n },\n scope: 'global',\n access: {\n view: 'public',\n create: 'group.editor',\n update: 'group.editor',\n delete: 'group.admin',\n },\n})\n"],"mappings":"oHAoE8C,OAAO,OAAO,CAAE,EAAG,GAAK,EAAG,EAAI,CAAC,EAE9E,SAAS,EAAe,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AAK,CAAC,EAGrD,SAAU,EAAM,KAAK,CAAE,SAAU,EAAK,CAAC,EAIvC,SAAU,EAAM,KAAK,CACnB,SAAU,GACV,QAAS,GACT,MAAO,CAAE,QAAS,CAAE,KAAM,UAAW,CAAE,CACzC,CAAC,EAID,KAAM,EAAM,OAAO,CACjB,SAAU,GACV,QAAS,GACT,MAAO,CAAE,QAAS,CAAE,KAAM,UAAW,CAAE,CACzC,CAAC,EAGD,MAAO,EAAM,OAAO,CAAE,QAAS,EAAK,CAAC,EACrC,OAAQ,EAAM,OAAO,CAAE,QAAS,EAAK,CAAC,EAWtC,WAAY,EAAM,KAAK,EAGvB,UAAW,EAAM,OAAO,CACtB,QAAS,CAAC,QAAS,QAAS,QAAS,WAAY,OAAO,EACxD,SAAU,GACV,QAAS,EACX,CAAC,CACH,EACA,UAAW,CACT,EAAS,UAAU,EACnB,EAAqB,EAIrB,EAAW,CACT,OAAQ,CAAC,WAAY,UAAW,WAAY,QAAS,MAAO,aAAa,EACzE,IAAK,CACH,OAAQ,CAAC,WAAY,QAAS,MAAO,aAAa,EAClD,SAAU,QACZ,EACA,WAAa,IAAS,CACpB,GAAI,EAAI,GACR,MAAQ,EAAI,OAAiC,EAAI,SACjD,YAAa,EAAI,QACnB,EACF,CAAC,CACH,EACA,MAAO,CACL,KAAM,CAMJ,OAAQ,CAAC,QAAS,WAAY,OAAQ,WAAW,EACjD,QAAS,CAAC,QAAS,MAAM,CAC3B,CACF,EACA,MAAO,SACP,OAAQ,CACN,KAAM,SACN,OAAQ,eACR,OAAQ,eACR,OAAQ,aACV,CACF,CAAC"}
@@ -0,0 +1,2 @@
1
+ import{t as e}from"./rolldown-runtime-DK3Fl9T5.mjs";import{a as t}from"./focal-point-BWhtJzef.mjs";import{behavior as n,defineEntity as r,field as i,searchable as a}from"@murumets-ee/entity";import{z as o}from"zod";function s(e){if(!(`focalPoint`in e))return e;let n=e.focalPoint;if(n==null||t(n))return e;throw new o.ZodError([{code:`custom`,path:[`focalPoint`],message:`focalPoint must be { x, y } with both between 0 and 1, or null.`}])}function c(e){if(e.keys.includes(`focalPoint`))throw new o.ZodError([{code:`custom`,path:[`focalPoint`],message:`bulk update on '${e.entityName}' cannot write 'focalPoint': updateMany runs no per-row hooks, so the value would bypass its shape check. Update each row individually.`}])}function l(){return{name:`focalPointValidation`,hooks:{beforeCreate:async e=>s(e),beforeUpdate:async(e,t)=>s(t)},assertBulkUpdate:c}}var u=e({Media:()=>d});const d=r({name:`media`,fields:{title:i.text({translatable:!0}),alt:i.text({translatable:!0}),description:i.text({translatable:!0}),fileKey:i.text({required:!0,indexed:!0}),filename:i.text({required:!0}),mimeType:i.text({required:!0,indexed:!0,admin:{display:{type:`mimeType`}}}),size:i.number({required:!0,integer:!0,admin:{display:{type:`filesize`}}}),width:i.number({integer:!0}),height:i.number({integer:!0}),focalPoint:i.json(),mediaType:i.select({options:[`image`,`video`,`audio`,`document`,`other`],required:!0,indexed:!0})},behaviors:[n.auditable(),l(),a({fields:[`filename`,`fileKey`,`mimeType`,`title`,`alt`,`description`],fts:{fields:[`filename`,`title`,`alt`,`description`],language:`simple`},projection:e=>({id:e.id,label:e.title??e.filename,description:e.mimeType})})],admin:{list:{fields:[`title`,`mimeType`,`size`,`createdAt`],layouts:[`table`,`grid`]}},scope:`global`,access:{view:`public`,create:`group.editor`,update:`group.editor`,delete:`group.admin`}});export{u as n,d as t};
2
+ //# sourceMappingURL=entity-DKFCdQJT.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"entity-DKFCdQJT.mjs","names":[],"sources":["../src/crop/focal-point-validation.ts","../src/entity.ts"],"sourcesContent":["/**\n * `focalPointValidation()` — the write guard on `media.focalPoint`.\n *\n * `field.json()` validates as the permissive JSON union on purpose, so without\n * this hook an editor's PATCH could park any shape in the column — a megabyte\n * string, a nested object — and every public page drawing the photograph would\n * carry it, because the projection hands the value to the render. CLAUDE.md's\n * \"validate at the boundary\", on the one column this package adds.\n *\n * Errors are `ZodError`s, so the admin API answers 400 with an issue pathed at\n * `focalPoint` rather than a 500 — the contract `menuEntityTypesValidation()`\n * already relies on.\n */\n\nimport type { Behavior, BulkUpdateInfo } from '@murumets-ee/entity'\nimport { z } from 'zod'\nimport { isFocalPoint } from './focal-point.js'\n\n/**\n * `null` is a legitimate value — it means \"no focal point\", which renders as the\n * centre (D010). Anything else must be exactly `{x, y}` in `[0, 1]`.\n */\nfunction validateFocalPoint(data: Record<string, unknown>): Record<string, unknown> {\n // A payload without the key is a partial update that does not touch the\n // column. Defaulting it here would let a title-only PATCH reset the point.\n if (!('focalPoint' in data)) return data\n const value = data.focalPoint\n if (value === null || value === undefined || isFocalPoint(value)) return data\n throw new z.ZodError([\n {\n code: 'custom',\n path: ['focalPoint'],\n message: 'focalPoint must be { x, y } with both between 0 and 1, or null.',\n },\n ])\n}\n\n/**\n * `updateMany` runs no per-row hooks, so `beforeUpdate` never sees a bulk write.\n * Refused rather than validated: `BulkUpdateInfo` is deliberately shape-only (it\n * names the columns, never the values), and \"every photograph has the same\n * subject position\" is not an intent anyone has. A migration is the tool for a\n * one-off backfill.\n */\nfunction assertNoBulkFocalPointWrite(info: BulkUpdateInfo): void {\n if (!info.keys.includes('focalPoint')) return\n throw new z.ZodError([\n {\n code: 'custom',\n path: ['focalPoint'],\n message:\n `bulk update on '${info.entityName}' cannot write 'focalPoint': updateMany runs no ` +\n 'per-row hooks, so the value would bypass its shape check. Update each row individually.',\n },\n ])\n}\n\n/**\n * Contributes NO fields — the empty map `Record<never, never>`, not\n * `Record<string, never>`, which would merge into the entity's field map and\n * collapse every field to `never`.\n */\nexport function focalPointValidation(): Behavior<Record<never, never>, 'focalPointValidation'> {\n return {\n name: 'focalPointValidation',\n hooks: {\n beforeCreate: async (data) => validateFocalPoint(data),\n beforeUpdate: async (_id, data) => validateFocalPoint(data),\n },\n assertBulkUpdate: assertNoBulkFocalPointWrite,\n }\n}\n","/**\n * Pre-defined Media entity.\n *\n * Auto-registered by the media() plugin — users do NOT add this to their entities array.\n * Connected to toolkit_files via the fileKey field (stores the StorageClient file key).\n *\n * @example\n * ```typescript\n * import { media } from '@murumets-ee/media/plugin'\n *\n * export default defineConfig({\n * plugins: [storage(), media()],\n * // Media entity is auto-added — no need to list it here\n * })\n * ```\n */\n\nimport { behavior, defineEntity, field, searchable } from '@murumets-ee/entity'\nimport { focalPointValidation } from './crop/focal-point-validation.js'\n\nexport const Media = defineEntity({\n name: 'media',\n fields: {\n // --- Display metadata (editable, translatable) ---\n title: field.text({ translatable: true }),\n alt: field.text({ translatable: true }),\n description: field.text({ translatable: true }),\n\n // --- File linkage (set on upload, immutable in practice) ---\n /** Key into toolkit_files table (e.g., 'uploads/2026/02/uuid/photo.jpg') */\n fileKey: field.text({ required: true, indexed: true }),\n\n // --- File metadata (set on upload) ---\n filename: field.text({ required: true }),\n // Drawn as an icon in the admin list (a film for `video/mp4`), not the raw\n // string — declared on the field, so any list of media reads the same\n // (entity-table D008).\n mimeType: field.text({\n required: true,\n indexed: true,\n admin: { display: { type: 'mimeType' } },\n }),\n // Bytes, drawn as \"1.5 MB\" in the operator's locale in the admin list\n // (entity-table D008). Hidden by default — an unindexed number is — and one\n // click away in the View menu.\n size: field.number({\n required: true,\n integer: true,\n admin: { display: { type: 'filesize' } },\n }),\n\n // --- Image-specific metadata (client-measured on upload) ---\n width: field.number({ integer: true }),\n height: field.number({ integer: true }),\n /**\n * Where the subject is, as `{ x, y }` fractions of the image — never pixels,\n * so it survives the file being replaced at another resolution (images\n * D002). A shaped slot crops around it (`@murumets-ee/media/crop`).\n *\n * Nullable, and `null` means the centre: an absent point and `{0.5, 0.5}`\n * render identically, so no reader branches on a legacy row (D010). The\n * shape is enforced by `focalPointValidation()` below — `field.json()` on\n * its own accepts any JSON.\n */\n focalPoint: field.json(),\n\n // --- Classification (derived from mimeType on upload) ---\n mediaType: field.select({\n options: ['image', 'video', 'audio', 'document', 'other'] as const,\n required: true,\n indexed: true,\n }),\n },\n behaviors: [\n behavior.auditable(),\n focalPointValidation(),\n // filename / fileKey / mimeType live on the main table.\n // title/alt/description are translatable — their tsvector goes on\n // media_translations so non-default-locale callers still get FTS.\n searchable({\n fields: ['filename', 'fileKey', 'mimeType', 'title', 'alt', 'description'],\n fts: {\n fields: ['filename', 'title', 'alt', 'description'],\n language: 'simple',\n },\n projection: (row) => ({\n id: row.id as string,\n label: (row.title as string | undefined) ?? (row.filename as string),\n description: row.mimeType as string,\n }),\n }),\n ],\n admin: {\n list: {\n // Title first (its own row-link column), then the type — the icon\n // display already draws it, so the raw `mimeType` string is not a\n // second column — size and when it was added. `fileKey` (the raw\n // storage path) and `mediaType` (redundant with the icon) stay off by\n // default, one View-menu click away (entity-table PR06 §6).\n fields: ['title', 'mimeType', 'size', 'createdAt'],\n layouts: ['table', 'grid'],\n },\n },\n scope: 'global',\n access: {\n view: 'public',\n create: 'group.editor',\n update: 'group.editor',\n delete: 'group.admin',\n },\n})\n"],"mappings":"uNAsBA,SAAS,EAAmB,EAAwD,CAGlF,GAAI,EAAE,eAAgB,GAAO,OAAO,EACpC,IAAM,EAAQ,EAAK,WACnB,GAAI,GAAU,MAA+B,EAAa,CAAK,EAAG,OAAO,EACzE,MAAM,IAAI,EAAE,SAAS,CACnB,CACE,KAAM,SACN,KAAM,CAAC,YAAY,EACnB,QAAS,iEACX,CACF,CAAC,CACH,CASA,SAAS,EAA4B,EAA4B,CAC1D,KAAK,KAAK,SAAS,YAAY,EACpC,MAAM,IAAI,EAAE,SAAS,CACnB,CACE,KAAM,SACN,KAAM,CAAC,YAAY,EACnB,QACE,mBAAmB,EAAK,WAAW,wIAEvC,CACF,CAAC,CACH,CAOA,SAAgB,GAA+E,CAC7F,MAAO,CACL,KAAM,uBACN,MAAO,CACL,aAAc,KAAO,IAAS,EAAmB,CAAI,EACrD,aAAc,MAAO,EAAK,IAAS,EAAmB,CAAI,CAC5D,EACA,iBAAkB,CACpB,CACF,wBCnDA,MAAa,EAAQ,EAAa,CAChC,KAAM,QACN,OAAQ,CAEN,MAAO,EAAM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`&&Number.isFinite(e)&&e>=0&&e<=1}function n(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let n=Object.keys(e);if(n.length!==2||!n.includes(`x`)||!n.includes(`y`))return!1;let{x:r,y:i}=e;return t(r)&&t(i)}function r(t){return n(t)?t:e}function i(e){return e.x===.5&&e.y===.5}function a(e,t,n){return Math.min(Math.max(e,t),n)}function o(e,t){return e>0&&Number.isFinite(e)&&t>0&&Number.isFinite(t)?e>t?{w:t/e,h:1}:{w:1,h:e/t}:{w:1,h:1}}function s(e,t){return a(e-t/2,0,1-t)}function c(e,t,n){let r=o(t,n);return{x:s(e.x,r.w),y:s(e.y,r.h),w:r.w,h:r.h}}function l(e,t,n){let r=c(e,t,n);return{x:r.w<1?r.x/(1-r.w):.5,y:r.h<1?r.y/(1-r.h):.5}}function u(e){return`${d(e.x)} ${d(e.y)}`}function d(e){return`${Math.round(e*1e4)/100}%`}export{n as a,o as c,i,c as n,l as o,u as r,r as s,e as t};
2
+ //# sourceMappingURL=focal-point-BWhtJzef.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"focal-point-BWhtJzef.mjs","names":[],"sources":["../src/crop/focal-point.ts"],"sourcesContent":["/**\n * The focal point, and every number derived from it — ONE pure module.\n *\n * A photograph's focal point is stored once, on the media row, as a fraction of\n * the image (`{x, y}` in `[0, 1]`, images D002). Two consumers turn it into a\n * crop: the browser, through `object-position` on a shaped slot (this PR), and\n * sharp, through `extract()` before a shaped variant is resized (images PR04).\n * Both import this file, so the generated crop and the CSS crop cannot\n * disagree — they are the same arithmetic, not two copies of it.\n *\n * No DOM, no sharp, no database. It is imported by `@murumets-ee/blocks`' render\n * spine, which ships to every visitor's browser, so it must stay small and must\n * never import anything.\n *\n * ## Fractions, never pixels\n *\n * A pixel rect breaks the moment the source file is replaced at a different\n * resolution, and this toolkit's stored `width`/`height` are client-measured and\n * can be wrong (images R003). A fraction survives both.\n *\n * ## Why `object-position` is NOT `focal × 100%`\n *\n * `object-position` is an ALIGNMENT percentage: `75%` puts the image's 75% point\n * at the BOX's 75% point, not at its centre (css-backgrounds-3, \"the point 75%\n * across … is to be placed at the point 75% across the area\"). The naive\n * `object-position: {f·100}%` is therefore wrong by `|f − 0.5| × box_width` —\n * exactly zero for a centred subject and 50% of the box at the edges, which is\n * why it survives review (R002). The conversion, per axis:\n *\n * ```\n * w_vis = C / I // visible window, as a fraction of the image\n * L = clamp(f − w_vis / 2, 0, 1 − w_vis) // the window's leading edge\n * P = L / (1 − w_vis) // the object-position fraction\n * ```\n *\n * `P` depends on the CONTAINER's ratio through `w_vis`, which is why it is\n * computed at render and never stored (D002 rules out storing it).\n *\n * ## Absent and centre are the same thing\n *\n * {@link readFocalPoint} turns every absent, malformed or out-of-range value into\n * `{0.5, 0.5}`, and the centre produces `object-position: 50% 50%`, which is\n * CSS's initial value. So a legacy row with no focal point and a row whose focal\n * point is the centre render identically, and nothing downstream branches on\n * the difference (D010).\n */\n\n/**\n * A point in the image, as fractions of its width and height. Both in `[0, 1]`.\n *\n * A `type`, not an `interface`, on purpose: it is stored in a `field.json()`\n * column, and only a type alias is assignable to the entity's `JsonValue`\n * (an interface has no implicit index signature).\n */\nexport type FocalPoint = {\n readonly x: number\n readonly y: number\n}\n\n/** A rectangle in the image, as fractions of its width and height. */\nexport type FractionalRect = {\n readonly x: number\n readonly y: number\n readonly w: number\n readonly h: number\n}\n\n/** The default — and what every absent or unusable focal point means. */\nexport const CENTRE_FOCAL_POINT: FocalPoint = Object.freeze({ x: 0.5, y: 0.5 })\n\nfunction isUnitFraction(value: unknown): value is number {\n return typeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= 1\n}\n\n/**\n * Is `value` a storable focal point — exactly `{x, y}`, both finite fractions?\n *\n * STRICT, because it guards a WRITE (the media row's `focalPoint` column). An\n * extra key is refused rather than stripped: a JSON column that stores what it\n * was sent would otherwise accept `{x, y, notes: '<a megabyte>'}` and hand it to\n * every reader of every page that draws the photograph.\n */\nexport function isFocalPoint(value: unknown): value is FocalPoint {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false\n const keys = Object.keys(value)\n if (keys.length !== 2 || !keys.includes('x') || !keys.includes('y')) return false\n const { x, y } = value as { x: unknown; y: unknown }\n return isUnitFraction(x) && isUnitFraction(y)\n}\n\n/**\n * The focal point to RENDER with, from whatever a projection carried.\n *\n * LENIENT, because it guards a READ: an absent, null or malformed value is the\n * centre, never a throw. A render that threw on a bad stored value would take\n * the whole page down over one photograph's crop.\n */\nexport function readFocalPoint(value: unknown): FocalPoint {\n return isFocalPoint(value) ? value : CENTRE_FOCAL_POINT\n}\n\n/** Is this the centre — the point that needs no `object-position` at all? */\nexport function isCentreFocalPoint(focal: FocalPoint): boolean {\n return focal.x === 0.5 && focal.y === 0.5\n}\n\nfunction clamp(value: number, min: number, max: number): number {\n return Math.min(Math.max(value, min), max)\n}\n\n/**\n * The window a `cover` crop leaves visible, as a fraction of the image on each\n * axis.\n *\n * Under `object-fit: cover` the image is scaled until it covers the box, so at\n * most ONE axis overflows and the other is exactly `1`. `imageRatio` and\n * `boxRatio` are width / height. A ratio that is not a positive finite number\n * is a caller bug; it is answered with \"nothing overflows\" (`{1, 1}`), which\n * renders as today's centre crop rather than as `NaN%`.\n */\nexport function visibleWindow(\n imageRatio: number,\n boxRatio: number,\n): { readonly w: number; readonly h: number } {\n if (!(imageRatio > 0 && Number.isFinite(imageRatio) && boxRatio > 0 && Number.isFinite(boxRatio)))\n return { w: 1, h: 1 }\n // Image wider than the box → the horizontal axis overflows.\n if (imageRatio > boxRatio) return { w: boxRatio / imageRatio, h: 1 }\n return { w: 1, h: imageRatio / boxRatio }\n}\n\n/**\n * One axis of the conversion: the window's leading edge `L`, clamped so the\n * window never leaves the image.\n *\n * Clamping `L` to `[0, 1 − w_vis]` is exactly equivalent to clamping the\n * resulting `object-position` to `[0, 1]`, so \"never reveal background\" has one\n * spelling here rather than two (R002).\n */\nfunction windowStart(focal: number, visible: number): number {\n return clamp(focal - visible / 2, 0, 1 - visible)\n}\n\n/**\n * The crop a focal point implies for a box of `boxRatio`, as a fractional rect\n * of the image — the region sharp will `extract()` (images PR04) and the region\n * the browser shows through {@link objectPositionFor}.\n */\nexport function focalCropRect(\n focal: FocalPoint,\n imageRatio: number,\n boxRatio: number,\n): FractionalRect {\n const visible = visibleWindow(imageRatio, boxRatio)\n return {\n x: windowStart(focal.x, visible.w),\n y: windowStart(focal.y, visible.h),\n w: visible.w,\n h: visible.h,\n }\n}\n\n/**\n * The `object-position` fractions that make a `cover`-fitted image show\n * {@link focalCropRect}'s window.\n *\n * An axis that does not overflow (`w_vis == 1`) has no position to choose —\n * `object-position` is inert on it — so it answers `0.5`, CSS's own default.\n * That keeps the centre case literally `{0.5, 0.5}` and the emitted CSS\n * byte-comparable with a slot that has no focal point.\n */\nexport function objectPositionFor(\n focal: FocalPoint,\n imageRatio: number,\n boxRatio: number,\n): FocalPoint {\n const rect = focalCropRect(focal, imageRatio, boxRatio)\n return {\n x: rect.w < 1 ? rect.x / (1 - rect.w) : 0.5,\n y: rect.h < 1 ? rect.y / (1 - rect.h) : 0.5,\n }\n}\n\n/**\n * Format a position as a CSS `object-position` value: two percentages, rounded\n * to two decimals so the emitted markup is stable across floating-point noise\n * (`33.33% 50%`, not `33.333333333333336% 50%`).\n */\nexport function formatObjectPosition(position: FocalPoint): string {\n return `${percent(position.x)} ${percent(position.y)}`\n}\n\nfunction percent(fraction: number): string {\n return `${Math.round(fraction * 10000) / 100}%`\n}\n"],"mappings":"AAoEA,MAAa,EAAiC,OAAO,OAAO,CAAE,EAAG,GAAK,EAAG,EAAI,CAAC,EAE9E,SAAS,EAAe,EAAiC,CACvD,OAAO,OAAO,GAAU,UAAY,OAAO,SAAS,CAAK,GAAK,GAAS,GAAK,GAAS,CACvF,CAUA,SAAgB,EAAa,EAAqC,CAChE,GAAI,OAAO,GAAU,WAAY,GAAkB,MAAM,QAAQ,CAAK,EAAG,MAAO,GAChF,IAAM,EAAO,OAAO,KAAK,CAAK,EAC9B,GA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ACjE,MAAO,GAAG,EAAQ,EAAS,CAAC,EAAE,GAAG,EAAQ,EAAS,CAAC,GACrD,CAEA,SAAS,EAAQ,EAA0B,CACzC,MAAO,GAAG,KAAK,MAAM,EAAW,GAAK,EAAI,IAAI,EAC/C"}
@@ -0,0 +1,125 @@
1
+ //#region src/crop/focal-point.d.ts
2
+ /**
3
+ * The focal point, and every number derived from it — ONE pure module.
4
+ *
5
+ * A photograph's focal point is stored once, on the media row, as a fraction of
6
+ * the image (`{x, y}` in `[0, 1]`, images D002). Two consumers turn it into a
7
+ * crop: the browser, through `object-position` on a shaped slot (this PR), and
8
+ * sharp, through `extract()` before a shaped variant is resized (images PR04).
9
+ * Both import this file, so the generated crop and the CSS crop cannot
10
+ * disagree — they are the same arithmetic, not two copies of it.
11
+ *
12
+ * No DOM, no sharp, no database. It is imported by `@murumets-ee/blocks`' render
13
+ * spine, which ships to every visitor's browser, so it must stay small and must
14
+ * never import anything.
15
+ *
16
+ * ## Fractions, never pixels
17
+ *
18
+ * A pixel rect breaks the moment the source file is replaced at a different
19
+ * resolution, and this toolkit's stored `width`/`height` are client-measured and
20
+ * can be wrong (images R003). A fraction survives both.
21
+ *
22
+ * ## Why `object-position` is NOT `focal × 100%`
23
+ *
24
+ * `object-position` is an ALIGNMENT percentage: `75%` puts the image's 75% point
25
+ * at the BOX's 75% point, not at its centre (css-backgrounds-3, "the point 75%
26
+ * across … is to be placed at the point 75% across the area"). The naive
27
+ * `object-position: {f·100}%` is therefore wrong by `|f − 0.5| × box_width` —
28
+ * exactly zero for a centred subject and 50% of the box at the edges, which is
29
+ * why it survives review (R002). The conversion, per axis:
30
+ *
31
+ * ```
32
+ * w_vis = C / I // visible window, as a fraction of the image
33
+ * L = clamp(f − w_vis / 2, 0, 1 − w_vis) // the window's leading edge
34
+ * P = L / (1 − w_vis) // the object-position fraction
35
+ * ```
36
+ *
37
+ * `P` depends on the CONTAINER's ratio through `w_vis`, which is why it is
38
+ * computed at render and never stored (D002 rules out storing it).
39
+ *
40
+ * ## Absent and centre are the same thing
41
+ *
42
+ * {@link readFocalPoint} turns every absent, malformed or out-of-range value into
43
+ * `{0.5, 0.5}`, and the centre produces `object-position: 50% 50%`, which is
44
+ * CSS's initial value. So a legacy row with no focal point and a row whose focal
45
+ * point is the centre render identically, and nothing downstream branches on
46
+ * the difference (D010).
47
+ */
48
+ /**
49
+ * A point in the image, as fractions of its width and height. Both in `[0, 1]`.
50
+ *
51
+ * A `type`, not an `interface`, on purpose: it is stored in a `field.json()`
52
+ * column, and only a type alias is assignable to the entity's `JsonValue`
53
+ * (an interface has no implicit index signature).
54
+ */
55
+ type FocalPoint = {
56
+ readonly x: number;
57
+ readonly y: number;
58
+ };
59
+ /** A rectangle in the image, as fractions of its width and height. */
60
+ type FractionalRect = {
61
+ readonly x: number;
62
+ readonly y: number;
63
+ readonly w: number;
64
+ readonly h: number;
65
+ };
66
+ /** The default — and what every absent or unusable focal point means. */
67
+ declare const CENTRE_FOCAL_POINT: FocalPoint;
68
+ /**
69
+ * Is `value` a storable focal point — exactly `{x, y}`, both finite fractions?
70
+ *
71
+ * STRICT, because it guards a WRITE (the media row's `focalPoint` column). An
72
+ * extra key is refused rather than stripped: a JSON column that stores what it
73
+ * was sent would otherwise accept `{x, y, notes: '<a megabyte>'}` and hand it to
74
+ * every reader of every page that draws the photograph.
75
+ */
76
+ declare function isFocalPoint(value: unknown): value is FocalPoint;
77
+ /**
78
+ * The focal point to RENDER with, from whatever a projection carried.
79
+ *
80
+ * LENIENT, because it guards a READ: an absent, null or malformed value is the
81
+ * centre, never a throw. A render that threw on a bad stored value would take
82
+ * the whole page down over one photograph's crop.
83
+ */
84
+ declare function readFocalPoint(value: unknown): FocalPoint;
85
+ /** Is this the centre — the point that needs no `object-position` at all? */
86
+ declare function isCentreFocalPoint(focal: FocalPoint): boolean;
87
+ /**
88
+ * The window a `cover` crop leaves visible, as a fraction of the image on each
89
+ * axis.
90
+ *
91
+ * Under `object-fit: cover` the image is scaled until it covers the box, so at
92
+ * most ONE axis overflows and the other is exactly `1`. `imageRatio` and
93
+ * `boxRatio` are width / height. A ratio that is not a positive finite number
94
+ * is a caller bug; it is answered with "nothing overflows" (`{1, 1}`), which
95
+ * renders as today's centre crop rather than as `NaN%`.
96
+ */
97
+ declare function visibleWindow(imageRatio: number, boxRatio: number): {
98
+ readonly w: number;
99
+ readonly h: number;
100
+ };
101
+ /**
102
+ * The crop a focal point implies for a box of `boxRatio`, as a fractional rect
103
+ * of the image — the region sharp will `extract()` (images PR04) and the region
104
+ * the browser shows through {@link objectPositionFor}.
105
+ */
106
+ declare function focalCropRect(focal: FocalPoint, imageRatio: number, boxRatio: number): FractionalRect;
107
+ /**
108
+ * The `object-position` fractions that make a `cover`-fitted image show
109
+ * {@link focalCropRect}'s window.
110
+ *
111
+ * An axis that does not overflow (`w_vis == 1`) has no position to choose —
112
+ * `object-position` is inert on it — so it answers `0.5`, CSS's own default.
113
+ * That keeps the centre case literally `{0.5, 0.5}` and the emitted CSS
114
+ * byte-comparable with a slot that has no focal point.
115
+ */
116
+ declare function objectPositionFor(focal: FocalPoint, imageRatio: number, boxRatio: number): FocalPoint;
117
+ /**
118
+ * Format a position as a CSS `object-position` value: two percentages, rounded
119
+ * to two decimals so the emitted markup is stable across floating-point noise
120
+ * (`33.33% 50%`, not `33.333333333333336% 50%`).
121
+ */
122
+ declare function formatObjectPosition(position: FocalPoint): string;
123
+ //#endregion
124
+ export { formatObjectPosition as a, objectPositionFor as c, focalCropRect as i, readFocalPoint as l, FocalPoint as n, isCentreFocalPoint as o, FractionalRect as r, isFocalPoint as s, CENTRE_FOCAL_POINT as t, visibleWindow as u };
125
+ //# sourceMappingURL=focal-point-C_0drV03.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"focal-point-C_0drV03.d.mts","names":[],"sources":["../src/crop/focal-point.ts"],"mappings":";;AAsDA;;;;AAEY;AAIZ;;;;;;;;;AAIY;AAIZ;;;;AAA+E;AAc/E;;;;;;;;AAAiE;AAejE;;;;AAA0D;AAK1D;;;;AAAoD;AAkBpD;;;;;;;;;AAGmC;AAyBnC;;;KA9FY,UAAA;EAAA,SACD,CAAA;EAAA,SACA,CAAC;AAAA;;KAIA,cAAA;EAAA,SACD,CAAA;EAAA,SACA,CAAA;EAAA,SACA,CAAA;EAAA,SACA,CAAA;AAAA;;cAIE,kBAAA,EAAoB,UAA8C;;;;;;AA2GlE;AAab;;iBA1GgB,YAAA,CAAa,KAAA,YAAiB,KAAA,IAAS,UAAU;;AA0GR;;;;;;iBA3FzC,cAAA,CAAe,KAAA,YAAiB,UAAU;;iBAK1C,kBAAA,CAAmB,KAAiB,EAAV,UAAU;;;;;;;;;;;iBAkBpC,aAAA,CACd,UAAA,UACA,QAAA;EAAA,SACY,CAAA;EAAA,SAAoB,CAAA;AAAA;;;;;;iBAyBlB,aAAA,CACd,KAAA,EAAO,UAAA,EACP,UAAA,UACA,QAAA,WACC,cAAc;;;;;;;;;;iBAmBD,iBAAA,CACd,KAAA,EAAO,UAAA,EACP,UAAA,UACA,QAAA,WACC,UAAU;;;;;;iBAaG,oBAAA,CAAqB,QAAoB,EAAV,UAAU"}
@@ -0,0 +1,2 @@
1
+ import{z as e}from"zod";import{defineSettings as t,setting as n}from"@murumets-ee/settings/define";const r=e.object({width:e.number().int().positive().optional(),height:e.number().int().positive().optional(),fit:e.enum([`cover`,`contain`,`inside`,`outside`,`fill`]).optional(),format:e.enum([`webp`,`jpeg`,`png`,`avif`]).optional(),quality:e.number().int().min(1).max(100).optional()}).refine(e=>e.width!==void 0||e.height!==void 0,{message:`Style must have at least width or height`}),i=/^[a-z][a-z0-9_-]*$/,a=e.record(e.string(),r).superRefine((t,n)=>{for(let r of Object.keys(t))i.test(r)||n.addIssue({code:e.ZodIssueCode.custom,path:[r],message:`Invalid style name "${r}": must be lowercase alphanumeric (a-z, 0-9, -, _)`})}),o=t({namespace:`media.imageStyles`,scope:`global`,label:`Image Styles`,iconName:`image-down`,schema:{imageStyles:n.json({default:{thumbnail:{thumbnail:{width:200,height:200,fit:`cover`,format:`webp`,quality:80},card:{width:600,height:400,fit:`cover`,format:`webp`,quality:85},hero:{width:1920,height:800,fit:`cover`,format:`webp`,quality:85},full:{width:2400,fit:`inside`,format:`webp`,quality:90}}.thumbnail},label:`Image processing presets`,schema:a,renderer:`media.imageStyles`})}});export{o as imageStylesSettings};
2
+ //# sourceMappingURL=image-styles-settings-DEnu-V2E.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"image-styles-settings-ClIA2MJI.mjs","names":[],"sources":["../src/image-styles-settings.ts"],"sourcesContent":["/**\n * Settings definition for media image styles.\n *\n * Stores the full Record<string, ImageStyle> as a single JSON key\n * in the toolkit_settings table under namespace 'media.imageStyles'.\n *\n * The media() plugin seeds this from config on first boot.\n * After that, the settings DB is the source of truth.\n */\n\nimport { defineSettings, setting } from '@murumets-ee/settings/define'\nimport { z } from 'zod'\nimport type { ImageStyle } from './types.js'\n\n/**\n * Zod schema for the `imageStyles` value (Record<styleName, ImageStyle>).\n *\n * Drives both server-side validation (settings PATCH route) and\n * client-side resolverless surfacing of field errors. The keys (style\n * names) are constrained at validation time via `.superRefine` because\n * Zod records do not support per-key regex.\n */\nconst styleSchema = z\n .object({\n width: z.number().int().positive().optional(),\n height: z.number().int().positive().optional(),\n fit: z.enum(['cover', 'contain', 'inside', 'outside', 'fill']).optional(),\n format: z.enum(['webp', 'jpeg', 'png', 'avif']).optional(),\n quality: z.number().int().min(1).max(100).optional(),\n })\n .refine((s) => s.width !== undefined || s.height !== undefined, {\n message: 'Style must have at least width or height',\n })\n\nconst STYLE_NAME_RE = /^[a-z][a-z0-9_-]*$/\n\nconst imageStylesSchema = z\n .record(z.string(), styleSchema)\n .superRefine((styles, ctx) => {\n for (const name of Object.keys(styles)) {\n if (!STYLE_NAME_RE.test(name)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: [name],\n message: `Invalid style name \"${name}\": must be lowercase alphanumeric (a-z, 0-9, -, _)`,\n })\n }\n }\n })\n\n/**\n * Curated default image style presets for new projects.\n *\n * Consumers can register all of these via the media plugin config:\n * media({ imageStyles: defaultImageStyles })\n *\n * Or pick a subset:\n * media({ imageStyles: { thumbnail: defaultImageStyles.thumbnail } })\n *\n * The `imageStylesSettings` default below intentionally only includes\n * `thumbnail` — adding more here would auto-create them for every project\n * that uses the plugin without opting in.\n */\nexport const defaultImageStyles: Record<string, ImageStyle> = {\n thumbnail: { width: 200, height: 200, fit: 'cover', format: 'webp', quality: 80 },\n card: { width: 600, height: 400, fit: 'cover', format: 'webp', quality: 85 },\n hero: { width: 1920, height: 800, fit: 'cover', format: 'webp', quality: 85 },\n full: { width: 2400, fit: 'inside', format: 'webp', quality: 90 },\n}\n\nexport const imageStylesSettings = defineSettings({\n namespace: 'media.imageStyles',\n scope: 'global',\n label: 'Image Styles',\n iconName: 'image-down',\n schema: {\n imageStyles: setting.json<Record<string, ImageStyle>>({\n default: {\n thumbnail: defaultImageStyles.thumbnail,\n },\n label: 'Image processing presets',\n schema: imageStylesSchema,\n renderer: 'media.imageStyles',\n }),\n },\n})\n"],"mappings":"mGAsBA,MAAM,EAAc,EACjB,OAAO,CACN,MAAO,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,SAAS,CAAC,CAAC,SAAS,EAC5C,OAAQ,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,SAAS,CAAC,CAAC,SAAS,EAC7C,IAAK,EAAE,KAAK,CAAC,QAAS,UAAW,SAAU,UAAW,MAAM,CAAC,CAAC,CAAC,SAAS,EACxE,OAAQ,EAAE,KAAK,CAAC,OAAQ,OAAQ,MAAO,MAAM,CAAC,CAAC,CAAC,SAAS,EACzD,QAAS,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,SAAS,CACrD,CAAC,CAAC,CACD,OAAQ,GAAM,EAAE,QAAU,IAAA,IAAa,EAAE,SAAW,IAAA,GAAW,CAC9D,QAAS,0CACX,CAAC,EAEG,EAAgB,qBAEhB,EAAoB,EACvB,OAAO,EAAE,OAAO,EAAG,CAAW,CAAC,CAC/B,aAAa,EAAQ,IAAQ,CAC5B,IAAK,IAAM,KAAQ,OAAO,KAAK,CAAM,EAC9B,EAAc,KAAK,CAAI,GAC1B,EAAI,SAAS,CACX,KAAM,EAAE,aAAa,OACrB,KAAM,CAAC,CAAI,EACX,QAAS,uBAAuB,EAAK,mDACvC,CAAC,CAGP,CAAC,EAsBU,EAAsB,EAAe,CAChD,UAAW,oBACX,MAAO,SACP,MAAO,eACP,SAAU,aACV,OAAQ,CACN,YAAa,EAAQ,KAAiC,CACpD,QAAS,CACP,UAAW,CAdjB,UAAW,CAAE,MAAO,IAAK,OAAQ,IAAK,IAAK,QAAS,OAAQ,OAAQ,QAAS,EAAG,EAChF,KAAM,CAAE,MAAO,IAAK,OAAQ,IAAK,IAAK,QAAS,OAAQ,OAAQ,QAAS,EAAG,EAC3E,KAAM,CAAE,MAAO,KAAM,OAAQ,IAAK,IAAK,QAAS,OAAQ,OAAQ,QAAS,EAAG,EAC5E,KAAM,CAAE,MAAO,KAAM,IAAK,SAAU,OAAQ,OAAQ,QAAS,EAAG,CAW/C,EAAmB,SAChC,EACA,MAAO,2BACP,OAAQ,EACR,SAAU,mBACZ,CAAC,CACH,CACF,CAAC"}
1
+ {"version":3,"file":"image-styles-settings-DEnu-V2E.mjs","names":[],"sources":["../src/image-styles-settings.ts"],"sourcesContent":["/**\n * Settings definition for media image styles.\n *\n * Stores the full Record<string, ImageStyle> as a single JSON key\n * in the toolkit_settings table under namespace 'media.imageStyles'.\n *\n * The media() plugin seeds this from config on first boot.\n * After that, the settings DB is the source of truth.\n */\n\nimport { defineSettings, setting } from '@murumets-ee/settings/define'\nimport { z } from 'zod'\nimport type { ImageStyle } from './types.js'\n\n/**\n * Zod schema for the `imageStyles` value (Record<styleName, ImageStyle>).\n *\n * Drives both server-side validation (settings PATCH route) and\n * client-side resolverless surfacing of field errors. The keys (style\n * names) are constrained at validation time via `.superRefine` because\n * Zod records do not support per-key regex.\n */\nconst styleSchema = z\n .object({\n width: z.number().int().positive().optional(),\n height: z.number().int().positive().optional(),\n fit: z.enum(['cover', 'contain', 'inside', 'outside', 'fill']).optional(),\n format: z.enum(['webp', 'jpeg', 'png', 'avif']).optional(),\n quality: z.number().int().min(1).max(100).optional(),\n })\n .refine((s) => s.width !== undefined || s.height !== undefined, {\n message: 'Style must have at least width or height',\n })\n\nconst STYLE_NAME_RE = /^[a-z][a-z0-9_-]*$/\n\nconst imageStylesSchema = z\n .record(z.string(), styleSchema)\n .superRefine((styles, ctx) => {\n for (const name of Object.keys(styles)) {\n if (!STYLE_NAME_RE.test(name)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: [name],\n message: `Invalid style name \"${name}\": must be lowercase alphanumeric (a-z, 0-9, -, _)`,\n })\n }\n }\n })\n\n/**\n * Curated default image style presets for new projects.\n *\n * Consumers can register all of these via the media plugin config:\n * media({ imageStyles: defaultImageStyles })\n *\n * Or pick a subset:\n * media({ imageStyles: { thumbnail: defaultImageStyles.thumbnail } })\n *\n * The `imageStylesSettings` default below intentionally only includes\n * `thumbnail` — adding more here would auto-create them for every project\n * that uses the plugin without opting in.\n */\nexport const defaultImageStyles: Record<string, ImageStyle> = {\n thumbnail: { width: 200, height: 200, fit: 'cover', format: 'webp', quality: 80 },\n card: { width: 600, height: 400, fit: 'cover', format: 'webp', quality: 85 },\n hero: { width: 1920, height: 800, fit: 'cover', format: 'webp', quality: 85 },\n full: { width: 2400, fit: 'inside', format: 'webp', quality: 90 },\n}\n\nexport const imageStylesSettings = defineSettings({\n namespace: 'media.imageStyles',\n scope: 'global',\n label: 'Image Styles',\n iconName: 'image-down',\n schema: {\n imageStyles: setting.json<Record<string, ImageStyle>>({\n default: {\n thumbnail: defaultImageStyles.thumbnail,\n },\n label: 'Image processing presets',\n schema: imageStylesSchema,\n renderer: 'media.imageStyles',\n }),\n },\n})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,QAAS,EAAG,EAC5E,KAAM,CAAE,MAAO,KAAM,IAAK,SAAU,OAAQ,OAAQ,QAAS,EAAG,CAW/C,EAAmB,SAChC,EACA,MAAO,2BACP,OAAQ,EACR,SAAU,mBACZ,CAAC,CACH,CACF,CAAC"}
@@ -1,4 +1,4 @@
1
- import { t as ImageStyle } from "./types-1idCpe1k.mjs";
1
+ import { t as ImageStyle } from "./types-CnORVkLZ.mjs";
2
2
 
3
3
  //#region src/image-styles-settings.d.ts
4
4
  /**
@@ -1,2 +1,2 @@
1
- import{defineSettings as e,setting as t}from"@murumets-ee/settings/define";import{z as n}from"zod";const r=n.object({width:n.number().int().positive().optional(),height:n.number().int().positive().optional(),fit:n.enum([`cover`,`contain`,`inside`,`outside`,`fill`]).optional(),format:n.enum([`webp`,`jpeg`,`png`,`avif`]).optional(),quality:n.number().int().min(1).max(100).optional()}).refine(e=>e.width!==void 0||e.height!==void 0,{message:`Style must have at least width or height`}),i=/^[a-z][a-z0-9_-]*$/,a=n.record(n.string(),r).superRefine((e,t)=>{for(let r of Object.keys(e))i.test(r)||t.addIssue({code:n.ZodIssueCode.custom,path:[r],message:`Invalid style name "${r}": must be lowercase alphanumeric (a-z, 0-9, -, _)`})}),o={thumbnail:{width:200,height:200,fit:`cover`,format:`webp`,quality:80},card:{width:600,height:400,fit:`cover`,format:`webp`,quality:85},hero:{width:1920,height:800,fit:`cover`,format:`webp`,quality:85},full:{width:2400,fit:`inside`,format:`webp`,quality:90}},s=e({namespace:`media.imageStyles`,scope:`global`,label:`Image Styles`,iconName:`image-down`,schema:{imageStyles:t.json({default:{thumbnail:o.thumbnail},label:`Image processing presets`,schema:a,renderer:`media.imageStyles`})}});export{o as defaultImageStyles,s as imageStylesSettings};
1
+ import{z as e}from"zod";import{defineSettings as t,setting as n}from"@murumets-ee/settings/define";const r=e.object({width:e.number().int().positive().optional(),height:e.number().int().positive().optional(),fit:e.enum([`cover`,`contain`,`inside`,`outside`,`fill`]).optional(),format:e.enum([`webp`,`jpeg`,`png`,`avif`]).optional(),quality:e.number().int().min(1).max(100).optional()}).refine(e=>e.width!==void 0||e.height!==void 0,{message:`Style must have at least width or height`}),i=/^[a-z][a-z0-9_-]*$/,a=e.record(e.string(),r).superRefine((t,n)=>{for(let r of Object.keys(t))i.test(r)||n.addIssue({code:e.ZodIssueCode.custom,path:[r],message:`Invalid style name "${r}": must be lowercase alphanumeric (a-z, 0-9, -, _)`})}),o={thumbnail:{width:200,height:200,fit:`cover`,format:`webp`,quality:80},card:{width:600,height:400,fit:`cover`,format:`webp`,quality:85},hero:{width:1920,height:800,fit:`cover`,format:`webp`,quality:85},full:{width:2400,fit:`inside`,format:`webp`,quality:90}},s=t({namespace:`media.imageStyles`,scope:`global`,label:`Image Styles`,iconName:`image-down`,schema:{imageStyles:n.json({default:{thumbnail:o.thumbnail},label:`Image processing presets`,schema:a,renderer:`media.imageStyles`})}});export{o as defaultImageStyles,s as imageStylesSettings};
2
2
  //# sourceMappingURL=image-styles-settings.mjs.map
package/dist/index.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { a as MediaRecord, c as MediaUploadResult, i as MediaPluginConfig, l as Media, n as MediaListOptions, o as MediaType, r as MediaListResult, s as MediaUploadOptions, t as ImageStyle } from "./types-1idCpe1k.mjs";
1
+ import { a as MediaRecord, c as MediaUploadResult, i as MediaPluginConfig, l as Media, n as MediaListOptions, o as MediaType, r as MediaListResult, s as MediaUploadOptions, t as ImageStyle } from "./types-CnORVkLZ.mjs";
2
2
  import { defaultImageStyles, imageStylesSettings } from "./image-styles-settings.mjs";
3
3
  //#region src/enrich.d.ts
4
4
  /**
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import{t as e}from"./entity-fxw-Qywj.mjs";import{defaultImageStyles as t,imageStylesSettings as n}from"./image-styles-settings.mjs";import"server-only";async function r(e,t,n=`thumbnail`){let r=Object.entries(e.allFields).filter(([,e])=>e.type===`media`).map(([e])=>e);if(r.length===0)return;let i=new Set;for(let e of t)for(let t of r){let n=e[t];typeof n==`string`&&n.length>0&&i.add(n)}if(i.size===0)return;let{getMediaClient:a}=await import(`./client.mjs`),o=await(await a()).getVariantUrls([...i],n);for(let e of t)for(let t of r){let n=e[t];typeof n==`string`&&o.has(n)&&(e[`${t}Url`]=o.get(n))}}export{e as Media,t as defaultImageStyles,r as enrichWithMediaUrls,n as imageStylesSettings};
1
+ import{t as e}from"./entity-DKFCdQJT.mjs";import{defaultImageStyles as t,imageStylesSettings as n}from"./image-styles-settings.mjs";import"server-only";async function r(e,t,n=`thumbnail`){let r=Object.entries(e.allFields).filter(([,e])=>e.type===`media`).map(([e])=>e);if(r.length===0)return;let i=new Set;for(let e of t)for(let t of r){let n=e[t];typeof n==`string`&&n.length>0&&i.add(n)}if(i.size===0)return;let{getMediaClient:a}=await import(`./client.mjs`),o=await(await a()).getVariantUrls([...i],n);for(let e of t)for(let t of r){let n=e[t];typeof n==`string`&&o.has(n)&&(e[`${t}Url`]=o.get(n))}}export{e as Media,t as defaultImageStyles,r as enrichWithMediaUrls,n as imageStylesSettings};
2
2
  //# sourceMappingURL=index.mjs.map