LCOV - code coverage report
Current view: top level - src/platform/assets/utils - assetMetadataUtils.ts Coverage Total Hit
Test: ComfyUI E2E Coverage Lines: 32.4 % 148 48
Test Date: 2026-11-17 04:17:53

            Line data    Source code
       1              : import type { Size2D as ImageDimensions } from '@comfyorg/shared-frontend-utils/geometry'
       2              : import type {
       3              :   AssetItem,
       4              :   ModelBrowserAsset
       5              : } from '@/platform/assets/schemas/assetSchema'
       6              : import { isCloud } from '@/platform/distribution/types'
       7              : import { isCivitaiUrl } from '@/utils/formatUtil'
       8              : 
       9              : // Reserved tag literals (mirror assetService's MODELS_TAG/MISSING_TAG). Kept
      10              : // local so this leaf util doesn't pull the heavier assetService -> i18n chain.
      11         2356 : const MODELS_TAG = 'models'
      12         2356 : const MISSING_TAG = 'missing'
      13              : 
      14              : /**
      15              :  * Type-safe utilities for extracting metadata from assets.
      16              :  * These utilities check user_metadata first, then metadata, then fallback.
      17              :  */
      18              : 
      19              : /**
      20              :  * Helper to get a string property from user_metadata or metadata
      21              :  */
      22         3220 : function getStringProperty(asset: AssetItem, key: string): string | undefined {
      23         3220 :   const userValue = asset.user_metadata?.[key]
      24         3220 :   if (typeof userValue === 'string') return userValue
      25              : 
      26         3220 :   const metaValue = asset.metadata?.[key]
      27         3220 :   if (typeof metaValue === 'string') return metaValue
      28              : 
      29              :   return undefined
      30              : }
      31              : 
      32              : /**
      33              :  * Safely extracts string description from asset metadata
      34              :  * Checks user_metadata first, then metadata, then returns null
      35              :  * @param asset - The asset to extract description from
      36              :  * @returns The description string or null if not present/not a string
      37              :  */
      38            0 : export function getAssetDescription(asset: AssetItem): string | null {
      39            0 :   return getStringProperty(asset, 'description') ?? null
      40              : }
      41              : 
      42              : /**
      43              :  * Safely extracts string base_model from asset metadata
      44              :  * Checks user_metadata first, then metadata, then returns null
      45              :  * @param asset - The asset to extract base_model from
      46              :  * @returns The base_model string or null if not present/not a string
      47              :  */
      48              : export function getAssetBaseModel(asset: AssetItem): string | null {
      49              :   return getStringProperty(asset, 'base_model') ?? null
      50              : }
      51              : 
      52              : /**
      53              :  * Extracts base models as an array from asset metadata
      54              :  * Checks user_metadata first, then metadata, then returns empty array
      55              :  * @param asset - The asset to extract base models from
      56              :  * @returns Array of base model strings
      57              :  */
      58         1896 : export function getAssetBaseModels(asset: AssetItem): string[] {
      59         1896 :   const baseModel =
      60              :     asset.user_metadata?.base_model ?? asset.metadata?.base_model
      61         1896 :   if (Array.isArray(baseModel)) {
      62            0 :     return baseModel.filter((m): m is string => typeof m === 'string')
      63              :   }
      64         1896 :   if (typeof baseModel === 'string' && baseModel) {
      65            0 :     return [baseModel]
      66              :   }
      67         1896 :   return []
      68              : }
      69              : 
      70              : /**
      71              :  * Gets the display name for an asset
      72              :  * Checks user_metadata.name, then metadata.name, then display_name, then asset.name
      73              :  * @param asset - The asset to get display name from
      74              :  * @returns The display name
      75              :  */
      76         3216 : export function getAssetDisplayName(asset: AssetItem): string {
      77         3216 :   return getStringProperty(asset, 'name') || asset.display_name || asset.name
      78              : }
      79              : 
      80              : /**
      81              :  * Constructs source URL from asset's source_arn
      82              :  * @param asset - The asset to extract source URL from
      83              :  * @returns The source URL or null if not present/parseable
      84              :  */
      85            0 : export function getAssetSourceUrl(asset: AssetItem): string | null {
      86            0 :   if (typeof asset.metadata?.repo_url === 'string') {
      87            0 :     return asset.metadata.repo_url
      88              :   }
      89              :   // Note: Reversed priority for backwards compatibility
      90            0 :   const sourceArn =
      91              :     asset.metadata?.source_arn ?? asset.user_metadata?.source_arn
      92            0 :   if (typeof sourceArn !== 'string') return null
      93              : 
      94            0 :   const civitaiMatch = sourceArn.match(
      95              :     /^civitai:model:(\d+):version:(\d+)(?::file:\d+)?$/
      96              :   )
      97            0 :   if (civitaiMatch) {
      98            0 :     const [, modelId, versionId] = civitaiMatch
      99            0 :     return `https://civitai.com/models/${modelId}?modelVersionId=${versionId}`
     100              :   }
     101              : 
     102            0 :   return null
     103              : }
     104              : 
     105              : /**
     106              :  * Extracts trigger phrases from asset metadata
     107              :  * Checks user_metadata first, then metadata, then returns empty array
     108              :  * @param asset - The asset to extract trigger phrases from
     109              :  * @returns Array of trigger phrases
     110              :  */
     111            0 : export function getAssetTriggerPhrases(asset: AssetItem): string[] {
     112            0 :   const phrases =
     113              :     asset.user_metadata?.trained_words ?? asset.metadata?.trained_words
     114            0 :   if (Array.isArray(phrases)) {
     115            0 :     return phrases.filter((p): p is string => typeof p === 'string')
     116              :   }
     117            0 :   if (typeof phrases === 'string') return [phrases]
     118            0 :   return []
     119              : }
     120              : 
     121              : /**
     122              :  * Extracts additional tags from asset user_metadata
     123              :  * @param asset - The asset to extract tags from
     124              :  * @returns Array of user-defined tags
     125              :  */
     126            0 : export function getAssetAdditionalTags(asset: AssetItem): string[] {
     127            0 :   const tags = asset.user_metadata?.additional_tags
     128            0 :   if (Array.isArray(tags)) {
     129            0 :     return tags.filter((t): t is string => typeof t === 'string')
     130              :   }
     131            0 :   return []
     132              : }
     133              : 
     134              : /**
     135              :  * Determines the source name from a URL
     136              :  * @param url - The source URL
     137              :  * @returns Human-readable source name
     138              :  */
     139            0 : export function getSourceName(url: string): string {
     140            0 :   if (isCivitaiUrl(url)) return 'Civitai'
     141            0 :   try {
     142            0 :     const hostname = new URL(url).hostname.toLowerCase()
     143            0 :     if (hostname === 'huggingface.co' || hostname.endsWith('.huggingface.co')) {
     144            0 :       return 'Hugging Face'
     145              :     }
     146              :   } catch {
     147              :     // fall through for invalid URLs
     148              :   }
     149            0 :   return 'Source'
     150              : }
     151              : 
     152              : /** Prefix for the namespaced tag that carries a model's folder category, e.g. `model_type:checkpoints`. */
     153         2356 : export const MODEL_TYPE_TAG_PREFIX = 'model_type:'
     154              : 
     155              : /**
     156              :  * Extracts the model type from asset tags as a bare (non-namespaced) value.
     157              :  * Never returns a raw `model_type:*` literal: this value feeds edit widgets
     158              :  * whose save path writes tags back verbatim, so a namespaced tag leaking
     159              :  * through here would round-trip the prefixed literal into the tag set.
     160              :  * @param asset - The asset to extract model type from
     161              :  * @returns The model type string or null if not present
     162              :  */
     163            0 : export function getAssetModelType(asset: AssetItem): string | null {
     164              :   const typeTag = asset.tags.find(
     165              :     (tag) => tag && tag !== MODELS_TAG && !tag.startsWith(MODEL_TYPE_TAG_PREFIX)
     166              :   )
     167            0 :   return typeTag ?? null
     168              : }
     169              : 
     170              : /**
     171              :  * Builds the namespaced subtype tag the backend stores in `model_type:` mode.
     172              :  * The argument is a discovery folder_name (e.g. `checkpoints`,
     173              :  * `ultralytics_bbox`); the backend keeps the bare directory-path twin in sync.
     174              :  * An already-namespaced input is returned unchanged rather than silently
     175              :  * double-prefixed.
     176              :  */
     177            0 : export function toModelTypeTag(folderName: string): string {
     178            0 :   if (folderName.startsWith(MODEL_TYPE_TAG_PREFIX)) return folderName
     179            0 :   return `${MODEL_TYPE_TAG_PREFIX}${folderName}`
     180              : }
     181              : 
     182              : /** Strips the `model_type:` prefix off each namespaced tag, dropping non-`model_type:` tags. */
     183          104 : function getModelTypeTagValues(asset: AssetItem): string[] {
     184          104 :   return asset.tags
     185              :     .filter((tag) => tag.startsWith(MODEL_TYPE_TAG_PREFIX))
     186              :     .map((tag) => tag.slice(MODEL_TYPE_TAG_PREFIX.length))
     187              :     .filter((tag) => tag.length > 0)
     188              : }
     189              : 
     190            0 : export function isModelTypeCovered(asset: AssetItem): boolean {
     191            0 :   return getModelTypeTagValues(asset).length > 0
     192              : }
     193              : 
     194              : /**
     195              :  * The asset's primary `model_type:` membership: the lexicographically-first of
     196              :  * its stripped `model_type:` values, or `undefined` for an uncovered asset.
     197              :  * Sorting makes the choice deterministic because the backend does not guarantee
     198              :  * the order of an asset's `model_type:` tags. This is the single membership a
     199              :  * re-type replaces and the value the edit dropdown / browser title reflect.
     200              :  */
     201            0 : function getPrimaryModelType(asset: AssetItem): string | undefined {
     202            0 :   return [...getModelTypeTagValues(asset)].sort()[0]
     203              : }
     204              : 
     205              : /**
     206              :  * Resolves the folder_name shown as the asset's current model type in the edit
     207              :  * dropdown. In `modelTypeMode` the primary `model_type:` value is authoritative
     208              :  * (covered assets); an uncovered asset with no `model_type:` tag falls back to
     209              :  * its bare subtype tag, mirroring the read-side grouping. Outside the mode this
     210              :  * is the legacy first-non-`models` tag.
     211              :  */
     212            0 : export function getEditableModelType(
     213              :   asset: AssetItem,
     214              :   modelTypeMode: boolean
     215              : ): string | null {
     216            0 :   if (modelTypeMode) {
     217            0 :     const primary = getPrimaryModelType(asset)
     218            0 :     if (primary !== undefined) return primary
     219              :   }
     220            0 :   return getAssetModelType(asset)
     221              : }
     222              : 
     223              : /**
     224              :  * Computes the tag set for re-typing a model asset to `newFolderName`. In
     225              :  * `modelTypeMode` only the primary `model_type:` membership is replaced: a
     226              :  * covered asset drops `model_type:<primary>` and its bare directory-path twin,
     227              :  * leaving any sibling `model_type:` memberships of a multi-type asset intact;
     228              :  * an uncovered asset drops its bare current type. The new
     229              :  * `model_type:<folder_name>` is then added (deduped if it already exists as a
     230              :  * sibling). Outside the mode it swaps the legacy bare subtype tag, preserving
     231              :  * the pre-namespace behavior.
     232              :  */
     233            0 : export function buildModelTypeTagUpdate(
     234              :   asset: AssetItem,
     235              :   newFolderName: string,
     236              :   modelTypeMode: boolean
     237              : ): string[] {
     238            0 :   if (!modelTypeMode) {
     239            0 :     const currentType = getAssetModelType(asset)
     240            0 :     return asset.tags.filter((tag) => tag !== currentType).concat(newFolderName)
     241              :   }
     242              : 
     243            0 :   const primary = getPrimaryModelType(asset)
     244            0 :   const currentBareType = getAssetModelType(asset)
     245            0 :   const tagsToRemove =
     246              :     primary !== undefined
     247              :       ? new Set([toModelTypeTag(primary), primary])
     248              :       : new Set(currentBareType ? [currentBareType] : [])
     249              : 
     250            0 :   const newTag = toModelTypeTag(newFolderName)
     251            0 :   const retained = asset.tags.filter((tag) => !tagsToRemove.has(tag))
     252            0 :   return retained.includes(newTag) ? retained : retained.concat(newTag)
     253              : }
     254              : 
     255              : /**
     256              :  * Save gate for a model-type change: returns the tag set to persist, or null
     257              :  * when the change must not be written (the type is read-only, or unchanged).
     258              :  * Keeps tag-set semantics in buildModelTypeTagUpdate; this only decides whether
     259              :  * to save.
     260              :  */
     261            0 : export function resolveModelTypeTagUpdate(
     262              :   asset: AssetItem,
     263              :   newFolderName: string,
     264              :   isEditable: boolean,
     265              :   modelTypeMode: boolean
     266              : ): string[] | null {
     267            0 :   if (!isEditable) return null
     268            0 :   if (getEditableModelType(asset, modelTypeMode) === newFolderName) return null
     269            0 :   return buildModelTypeTagUpdate(asset, newFolderName, modelTypeMode)
     270              : }
     271              : 
     272              : /** Legacy grouping: each non-`models` tag's top-level path segment. */
     273            3 : function getBareTagCategories(asset: AssetItem): string[] {
     274            3 :   return asset.tags
     275              :     .filter((tag) => tag !== MODELS_TAG && tag.length > 0)
     276              :     .map((tag) => tag.split('/')[0])
     277              : }
     278              : 
     279              : /**
     280              :  * Resolves the category keys a model asset is grouped under.
     281              :  *
     282              :  * `modelTypeMode` reflects whether the backend declares the `model_type:` tag
     283              :  * scheme (the `supports_model_type_tags` capability). When true, an asset's
     284              :  * `model_type:*` values are authoritative; an asset with no `model_type:` tag
     285              :  * still routes by its bare tags. When false (the default) categories come from
     286              :  * the legacy bare-tag top-level grouping and `model_type:` is ignored.
     287              :  */
     288          106 : export function getAssetCategories(
     289              :   asset: ModelBrowserAsset,
     290              :   modelTypeMode: boolean
     291              : ): string[] {
     292          106 :   if (asset.browserCategories) return asset.browserCategories
     293          106 :   if (modelTypeMode) {
     294          104 :     const modelTypes = getModelTypeTagValues(asset)
     295          104 :     if (modelTypes.length > 0) return modelTypes
     296            1 :     return getBareTagCategories(asset).filter(
     297              :       (category) => !category.startsWith(MODEL_TYPE_TAG_PREFIX)
     298              :     )
     299              :   }
     300              : 
     301            2 :   return getBareTagCategories(asset)
     302              : }
     303              : 
     304              : /**
     305              :  * Resolves the primary tag a browser surface titles itself after. In
     306              :  * `modelTypeMode` a covered asset uses its primary `model_type:*` value — the
     307              :  * key it groups under — while an uncovered asset keeps the legacy selection
     308              :  * (first non-`models` tag, verbatim, hierarchical paths intact). Outside the
     309              :  * mode this is exactly the legacy selection.
     310              :  */
     311            0 : export function getPrimaryCategoryTag(
     312              :   asset: AssetItem,
     313              :   modelTypeMode: boolean
     314              : ): string | undefined {
     315            0 :   if (modelTypeMode) {
     316            0 :     const primary = getPrimaryModelType(asset)
     317            0 :     if (primary !== undefined) return primary
     318            0 :     return asset.tags.find(
     319              :       (tag) => tag !== MODELS_TAG && !tag.startsWith(MODEL_TYPE_TAG_PREFIX)
     320              :     )
     321              :   }
     322            0 :   return asset.tags.find((tag) => tag !== MODELS_TAG)
     323              : }
     324              : 
     325              : /** Number of `parent/child` segments in a tag, used to pick the most specific. */
     326            0 : function pathDepth(tag: string): number {
     327            0 :   return tag.split('/').length
     328              : }
     329              : 
     330              : /** Removes the `model_type:` namespace prefix from a tag when present. */
     331            0 : export function stripModelTypePrefix(tag: string): string {
     332            0 :   return tag.startsWith(MODEL_TYPE_TAG_PREFIX)
     333              :     ? tag.slice(MODEL_TYPE_TAG_PREFIX.length)
     334              :     : tag
     335              : }
     336              : 
     337              : /**
     338              :  * Resolves the labels shown as an asset card's type badges.
     339              :  *
     340              :  * In `modelTypeMode` a covered asset badges every `model_type:*` value — the
     341              :  * same keys it groups under (`getAssetCategories`) — so a shared-root asset
     342              :  * tagged with several categories carries each of them; whichever category
     343              :  * view the card appears in is represented on the card. Uncovered assets (and
     344              :  * legacy mode) keep the original single selection: first non-`models` tag,
     345              :  * with bare hierarchical tags showing the segment after the first `/`.
     346              :  */
     347            0 : export function getAssetTypeBadges(
     348              :   asset: ModelBrowserAsset,
     349              :   modelTypeMode: boolean
     350              : ): string[] {
     351            0 :   if (asset.browserCategories) return asset.browserCategories
     352            0 :   if (modelTypeMode) {
     353            0 :     const modelTypes = getModelTypeTagValues(asset)
     354            0 :     if (modelTypes.length > 0) return modelTypes
     355              :   }
     356            0 :   const typeTag = asset.tags.find(
     357              :     (tag) =>
     358              :       tag !== MODELS_TAG &&
     359              :       !(modelTypeMode && tag.startsWith(MODEL_TYPE_TAG_PREFIX))
     360              :   )
     361            0 :   if (!typeTag) return []
     362            0 :   return [
     363              :     typeTag.includes('/') ? typeTag.slice(typeTag.indexOf('/') + 1) : typeTag
     364              :   ]
     365              : }
     366              : 
     367              : /**
     368              :  * Ordered node-category candidates for an asset, most specific first.
     369              :  *
     370              :  * Callers resolve a node provider by trying each candidate in order and taking
     371              :  * the first that maps to a provider. The full (possibly hierarchical) value is
     372              :  * kept so `modelToNodeStore`'s `parent/child` fallback still works.
     373              :  *
     374              :  * In `modelTypeMode` (backend declares `supports_model_type_tags`) candidates
     375              :  * come in two tiers. Tier 1: the stripped `model_type:*` values plus bare tags
     376              :  * *related* to one of them (equal to it, or extending it as a `parent/child`
     377              :  * path), ordered by descending depth — so a resolvable `LLM/Qwen-VL/...` twin
     378              :  * wins over a flat `model_type:LLM`, while ties keep `model_type:*` values
     379              :  * ahead of bare tags. Tier 2: unrelated bare tags (e.g. a user-added
     380              :  * `foo/bar`), tried only when nothing authoritative resolves — they can no
     381              :  * longer pre-empt a resolvable `model_type:*` value however deep they are.
     382              :  * An uncovered asset (no `model_type:` tag) routes by all its bare tags,
     383              :  * deepest first. Outside `modelTypeMode` the legacy first-non-reserved tag is
     384              :  * used verbatim.
     385              :  */
     386            0 : export function getAssetNodeCategoryCandidates(
     387              :   asset: ModelBrowserAsset,
     388              :   modelTypeMode: boolean
     389              : ): string[] {
     390            0 :   if (asset.browserCategories) return asset.browserCategories
     391            0 :   if (!modelTypeMode) {
     392            0 :     const legacy = asset.tags.find(
     393              :       (tag) => tag !== MODELS_TAG && tag !== MISSING_TAG
     394              :     )
     395            0 :     return legacy ? [legacy] : []
     396              :   }
     397              : 
     398            0 :   const bareTags = asset.tags.filter(
     399              :     (tag) =>
     400              :       tag !== MODELS_TAG &&
     401              :       tag !== MISSING_TAG &&
     402              :       !tag.startsWith(MODEL_TYPE_TAG_PREFIX)
     403              :   )
     404              : 
     405            0 :   const byDepthDesc = (a: string, b: string) => pathDepth(b) - pathDepth(a)
     406              : 
     407            0 :   const modelTypes = getModelTypeTagValues(asset)
     408            0 :   if (modelTypes.length === 0) return [...bareTags].sort(byDepthDesc)
     409              : 
     410            0 :   const isRelated = (tag: string) =>
     411              :     modelTypes.some((type) => tag === type || tag.startsWith(`${type}/`))
     412              : 
     413            0 :   return [
     414              :     ...[...new Set([...modelTypes, ...bareTags.filter(isRelated)])].sort(
     415              :       byDepthDesc
     416              :     ),
     417              :     ...bareTags.filter((tag) => !isRelated(tag)).sort(byDepthDesc)
     418              :   ]
     419              : }
     420              : 
     421              : /**
     422              :  * Extracts user description from asset user_metadata
     423              :  * @param asset - The asset to extract user description from
     424              :  * @returns The user description string or empty string if not present
     425              :  */
     426            0 : export function getAssetUserDescription(asset: AssetItem): string {
     427            0 :   return typeof asset.user_metadata?.user_description === 'string'
     428              :     ? asset.user_metadata.user_description
     429              :     : ''
     430              : }
     431              : 
     432              : /**
     433              :  * Gets the filename for an asset with fallback chain
     434              :  * Checks user_metadata.filename first, then metadata.filename, then asset.name.
     435              :  * Use this for serialized/identifier contexts (workflow widget values,
     436              :  * filename schema validation, missing-model matching) where we need the
     437              :  * canonical filename and MUST NOT substitute a display-only string.
     438              :  */
     439            4 : export function getAssetFilename(asset: AssetItem): string {
     440            4 :   return getStringProperty(asset, 'filename') ?? asset.name
     441              : }
     442              : 
     443              : /**
     444              :  * Resolves the filename that addresses an asset's *bytes* in storage — use
     445              :  * this to build the path a backend resolves to a real file (the
     446              :  * `createAnnotatedPath` input behind `/view` requests and widget values),
     447              :  * never to show the user. Cloud is content-addressed, so it returns the
     448              :  * content hash (`hash`); OSS is filesystem-backed, so it returns `name`.
     449              :  *
     450              :  * For a human-readable label use {@link getAssetDisplayFilename}; for a
     451              :  * serialized identifier (matching, validation) use {@link getAssetFilename}.
     452              :  *
     453              :  * TODO(BE-933/934): collapse to `asset.file_path ?? asset.name`.
     454              :  */
     455            7 : export function getAssetStoredFilename(
     456              :   asset: AssetItem,
     457              :   hash = asset.hash
     458              : ): string {
     459            7 :   return isCloud && hash ? hash : asset.name
     460              : }
     461              : 
     462              : /**
     463              :  * Human-readable filename for UI labels.
     464              :  * Fallback: user_metadata.filename → metadata.filename → display_name → asset.name.
     465              :  * For serialized identifiers use {@link getAssetFilename}.
     466              :  */
     467            0 : export function getAssetDisplayFilename(asset: AssetItem): string {
     468            0 :   return (
     469              :     getStringProperty(asset, 'filename') ?? asset.display_name ?? asset.name
     470              :   )
     471              : }
     472              : 
     473              : /**
     474              :  * Gets the title to render on an asset browser card / delete confirmation.
     475              :  * Prefers a user-curated name (user_metadata.name / metadata.name) when it
     476              :  * actually differs from asset.name, so a user-renamed model keeps its
     477              :  * display name. Falls through to {@link getAssetDisplayFilename} when the
     478              :  * curated name is absent or equal to asset.name (hash-keyed asset case).
     479              :  */
     480            0 : export function getAssetCardTitle(asset: AssetItem): string {
     481            0 :   const curatedName = getStringProperty(asset, 'name')
     482            0 :   if (curatedName && curatedName !== asset.name) return curatedName
     483            0 :   return getAssetDisplayFilename(asset)
     484              : }
     485              : export type { Size2D as ImageDimensions } from '@comfyorg/shared-frontend-utils/geometry'
     486              : 
     487              : /**
     488              :  * Type guard: a pixel dimension is a finite positive integer. `metadata` is
     489              :  * typed as `Record<string, unknown>`, so `typeof === 'number'` alone admits
     490              :  * NaN, Infinity, 0, negatives, and fractional values.
     491              :  */
     492          415 : function isValidDimension(value: unknown): value is number {
     493          415 :   return typeof value === 'number' && Number.isInteger(value) && value > 0
     494              : }
     495              : 
     496              : /**
     497              :  * Returns the original image dimensions from `asset.metadata.{width,height}`
     498              :  * when both pass shape validation, otherwise `undefined`. Callers should fall
     499              :  * back to the locally-computed `<img>.naturalWidth/Height`, which is correct
     500              :  * on runtimes that serve the original file but reports preview size on
     501              :  * runtimes that serve a downscaled preview.
     502              :  */
     503          415 : export function getAssetMetadataDimensions(
     504              :   asset: AssetItem | undefined
     505              : ): ImageDimensions | undefined {
     506          415 :   const w = asset?.metadata?.width
     507          415 :   const h = asset?.metadata?.height
     508          415 :   if (isValidDimension(w) && isValidDimension(h)) {
     509            0 :     return { width: w, height: h }
     510              :   }
     511              :   return undefined
     512              : }
     513              : 
     514              : /**
     515              :  * Resolves the image dimensions an asset card should display.
     516              :  *
     517              :  * Prefers the server-provided original dimensions from
     518              :  * {@link getAssetMetadataDimensions}. Only when those are absent does it fall
     519              :  * back to `renderedNaturalSize` — the natural size of the `<img>` the card
     520              :  * actually rendered — and only when that rendered image was the original file.
     521              :  *
     522              :  * A distinct `thumbnail_url` (one that differs from `preview_url`) means the
     523              :  * card rendered a downscaled preview, so `renderedNaturalSize` reflects the
     524              :  * preview's dimensions rather than the asset's. In that case this returns
     525              :  * `undefined` so the card shows no label rather than a wrong resolution.
     526              :  * On OSS, `thumbnail_url` and `preview_url` are the same URL (full-res),
     527              :  * so the guard correctly passes through `renderedNaturalSize`.
     528              :  */
     529          415 : export function resolveDisplayImageDimensions(
     530              :   asset: AssetItem | undefined,
     531              :   renderedNaturalSize: ImageDimensions | undefined
     532              : ): ImageDimensions | undefined {
     533          415 :   const fromMetadata = getAssetMetadataDimensions(asset)
     534          415 :   if (fromMetadata) return fromMetadata
     535          415 :   if (asset?.thumbnail_url && asset.thumbnail_url !== asset.preview_url)
     536            0 :     return undefined
     537          415 :   return renderedNaturalSize
     538              : }
     539              : 
     540              : /**
     541              :  * Returns the filename component the cloud `/api/view` endpoint resolves
     542              :  * for this asset — `hash` when present (cloud assets are hash-keyed
     543              :  * in storage), otherwise `asset.name`. Use this when constructing widget
     544              :  * values or media URLs that must round-trip through the view endpoint.
     545              :  */
     546         1896 : export function getAssetUrlFilename(asset: AssetItem): string {
     547         1896 :   return asset.hash ?? asset.name
     548              : }
     549              : 
     550              : /** `user_metadata.subfolder` when it is a string, else the directory of an unhashed asset's `loader_path`. */
     551         1903 : export function getOutputSubfolder(
     552              :   asset: Pick<AssetItem, 'hash' | 'loader_path' | 'user_metadata'>
     553              : ): string | undefined {
     554         1903 :   const subfolder = asset.user_metadata?.subfolder
     555         1903 :   if (typeof subfolder === 'string') return subfolder
     556         1903 :   if (asset.hash || !asset.loader_path) return undefined
     557            0 :   const separatorIndex = asset.loader_path.lastIndexOf('/')
     558         1903 :   return separatorIndex > 0
     559              :     ? asset.loader_path.slice(0, separatorIndex)
     560              :     : undefined
     561              : }
        

Generated by: LCOV version 2.0-1