LCOV - code coverage report
Current view: top level - packages/shared-frontend-utils/src - formatUtil.ts Coverage Total Hit
Test: ComfyUI E2E Coverage Lines: 70.3 % 195 137
Test Date: 2026-11-17 04:17:53

            Line data    Source code
       1              : import type { operations } from '@comfyorg/registry-types'
       2              : 
       3              : export function formatCamelCase(str: string): string {
       4              :   // Check if the string is camel case
       5              :   const isCamelCase = /^([A-Z][a-z]*)+$/.test(str)
       6              : 
       7              :   if (!isCamelCase) {
       8              :     return str // Return original string if not camel case
       9              :   }
      10              : 
      11              :   // Split the string into words, keeping acronyms together
      12              :   const words = str.split(/(?=[A-Z][a-z])|\d+/)
      13              : 
      14              :   // Process each word
      15              :   const processedWords = words.map((word) => {
      16              :     // If the word is all uppercase and longer than one character, it's likely an acronym
      17              :     if (word.length > 1 && word === word.toUpperCase()) {
      18              :       return word // Keep acronyms as is
      19              :     }
      20              :     // For other words, ensure the first letter is capitalized
      21              :     return word.charAt(0).toUpperCase() + word.slice(1)
      22              :   })
      23              : 
      24              :   // Join the words with spaces
      25              :   return processedWords.join(' ')
      26              : }
      27              : 
      28              : // Metadata cannot be associated with workflows, so extension encodes the mode.
      29         2356 : const JSON_SUFFIX = 'json'
      30         2356 : const APP_JSON_SUFFIX = `app.${JSON_SUFFIX}`
      31         2356 : const JSON_EXT = `.${JSON_SUFFIX}`
      32         2356 : const APP_JSON_EXT = `.${APP_JSON_SUFFIX}`
      33              : 
      34         2231 : export function appendJsonExt(path: string) {
      35         2231 :   if (!path.toLowerCase().endsWith(JSON_EXT)) {
      36         2138 :     path += JSON_EXT
      37              :   }
      38         2231 :   return path
      39              : }
      40              : 
      41              : export type WorkflowSuffix = typeof JSON_SUFFIX | typeof APP_JSON_SUFFIX
      42              : 
      43            2 : export function getWorkflowSuffix(
      44              :   suffix: string | null | undefined
      45              : ): WorkflowSuffix {
      46            2 :   return suffix === APP_JSON_SUFFIX ? APP_JSON_SUFFIX : JSON_SUFFIX
      47              : }
      48              : 
      49          116 : export function appendWorkflowJsonExt(path: string, isApp: boolean): string {
      50          116 :   return ensureWorkflowSuffix(path, isApp ? APP_JSON_SUFFIX : JSON_SUFFIX)
      51              : }
      52              : 
      53          118 : export function ensureWorkflowSuffix(
      54              :   name: string,
      55              :   suffix: WorkflowSuffix
      56              : ): string {
      57          118 :   const lower = name.toLowerCase()
      58          118 :   if (lower.endsWith(APP_JSON_EXT)) {
      59            0 :     name = name.slice(0, -APP_JSON_EXT.length)
      60          118 :   } else if (lower.endsWith(JSON_EXT)) {
      61            0 :     name = name.slice(0, -JSON_EXT.length)
      62              :   }
      63          118 :   return name + '.' + suffix
      64              : }
      65              : 
      66            0 : export function formatNumberWithSuffix(
      67              :   num: number,
      68              :   {
      69              :     precision = 1,
      70              :     roundToInt = false
      71              :   }: { precision?: number; roundToInt?: boolean } = {}
      72              : ): string {
      73            0 :   const suffixes = ['', 'k', 'm', 'b', 't']
      74            0 :   const absNum = Math.abs(num)
      75              : 
      76            0 :   if (absNum < 1000) {
      77            0 :     return roundToInt ? Math.round(num).toString() : num.toFixed(precision)
      78              :   }
      79              : 
      80            0 :   const exp = Math.min(Math.floor(Math.log10(absNum) / 3), suffixes.length - 1)
      81              :   const formattedNum = (num / Math.pow(1000, exp)).toFixed(precision)
      82              : 
      83            0 :   return `${formattedNum}${suffixes[exp]}`
      84              : }
      85              : 
      86           84 : export function formatSize(value?: number | null) {
      87           84 :   if (value === null || value === undefined) {
      88            0 :     return '-'
      89              :   }
      90              : 
      91           84 :   const bytes = value
      92           84 :   if (bytes === 0) return '0 B'
      93           84 :   const k = 1024
      94           84 :   const sizes = ['B', 'KB', 'MB', 'GB']
      95           84 :   const i = Math.floor(Math.log(bytes) / Math.log(k))
      96           84 :   return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))} ${sizes[i]}`
      97              : }
      98              : 
      99              : /**
     100              :  * Formats a commit hash by truncating long (40-char) hashes to 7 chars.
     101              :  * Returns the original string if not a valid full commit hash.
     102              :  */
     103            4 : export function formatCommitHash(value: string): string {
     104            4 :   if (/^[a-f0-9]{40}$/i.test(value)) {
     105            0 :     return value.slice(0, 7)
     106              :   }
     107            4 :   return value
     108              : }
     109              : 
     110              : /**
     111              :  * Returns various filename components.
     112              :  * Recognises compound extensions like `.app.json`.
     113              :  * Example:
     114              :  * - fullFilename: 'file.txt'       → { filename: 'file',  suffix: 'txt' }
     115              :  * - fullFilename: 'file.app.json'  → { filename: 'file',  suffix: 'app.json' }
     116              :  */
     117       276925 : export function getFilenameDetails(fullFilename: string) {
     118              :   const lower = fullFilename.toLowerCase()
     119       276925 :   if (
     120              :     lower.endsWith(APP_JSON_EXT) &&
     121              :     fullFilename.length > APP_JSON_EXT.length
     122              :   ) {
     123          521 :     return {
     124              :       filename: fullFilename.slice(0, -APP_JSON_EXT.length),
     125              :       suffix: APP_JSON_SUFFIX
     126              :     }
     127              :   }
     128       276404 :   const dotIndex = fullFilename.lastIndexOf('.')
     129       276925 :   if (dotIndex <= 0) return { filename: fullFilename, suffix: null }
     130       276404 :   return {
     131              :     filename: fullFilename.slice(0, dotIndex),
     132              :     suffix: fullFilename.slice(dotIndex + 1)
     133              :   }
     134              : }
     135              : 
     136              : /**
     137              :  * Returns various path components.
     138              :  * Example:
     139              :  * - path: 'dir/file.txt'
     140              :  * - directory: 'dir'
     141              :  * - fullFilename: 'file.txt'
     142              :  * - filename: 'file'
     143              :  * - suffix: 'txt'
     144              :  */
     145       272490 : export function getPathDetails(path: string) {
     146       272490 :   const directory = path.split('/').slice(0, -1).join('/')
     147       272490 :   const fullFilename = path.split('/').pop() ?? path
     148       272490 :   return { directory, fullFilename, ...getFilenameDetails(fullFilename) }
     149              : }
     150              : 
     151              : /**
     152              :  * Normalizes a string to be used as an i18n key.
     153              :  * Replaces dots with underscores.
     154              :  */
     155      8078037 : export function normalizeI18nKey(key: string) {
     156      8078037 :   return typeof key === 'string' ? key.replace(/\./g, '_') : ''
     157              : }
     158              : 
     159              : const VUE_I18N_BACKSLASH = /\\/g
     160              : const VUE_I18N_SYNTAX_CHARS = /[@${}|%]/g
     161              : 
     162              : /**
     163              :  * Escapes vue-i18n message syntax so arbitrary text can be stored as a locale
     164              :  * message and rendered verbatim by `t()`.
     165              :  *
     166              :  * Backslash is doubled rather than wrapped in a literal interpolation: since
     167              :  * vue-i18n 11 the message compiler reads `\` as an escape introducer, so a
     168              :  * backslash before an escaped character would swallow the `{` this emits, and
     169              :  * `{'\'}` would escape its own closing quote. Doubling must therefore run
     170              :  * first; the literal interpolations it emits contain no backslashes.
     171              :  *
     172              :  * Apply exactly once. This is NOT idempotent, because the escape output itself
     173              :  * contains `{`/`}`.
     174              :  *
     175              :  * Apply only to values read back through `t()`/`st()`. Values read through
     176              :  * `tm()`/`stRaw()` are never compiled, so escaping them renders the escape
     177              :  * syntax literally.
     178              :  */
     179              : export function escapeI18nMessage(text: string): string {
     180              :   if (typeof text !== 'string') return ''
     181              :   return text
     182              :     .replace(VUE_I18N_BACKSLASH, '\\\\')
     183              :     .replace(VUE_I18N_SYNTAX_CHARS, (char) => `{'${char}'}`)
     184              : }
     185              : 
     186              : /**
     187              :  * Takes a dynamic prompt in the format {opt1|opt2|{optA|optB}|} and randomly replaces groups. Supports C style comments.
     188              :  * @param input The dynamic prompt to process
     189              :  * @returns
     190              :  */
     191          250 : export function processDynamicPrompt(input: string): string {
     192              :   /*
     193              :    * Strips C-style line and block comments from a string
     194              :    */
     195          250 :   function stripComments(str: string) {
     196          250 :     return str.replace(/\/\*[\s\S]*?\*\/|\/\/.*/g, '')
     197              :   }
     198              : 
     199          250 :   let i = 0
     200          250 :   let result = ''
     201          250 :   input = stripComments(input)
     202              : 
     203          250 :   const handleEscape = () => {
     204              :     const nextChar = input[i++]
     205              :     return '\\' + nextChar
     206              :   }
     207              : 
     208            0 :   function parseChoiceBlock() {
     209              :     // Parse the content inside {}
     210            0 :     const options: string[] = []
     211            0 :     let choice = ''
     212            0 :     let depth = 0
     213              : 
     214            0 :     while (i < input.length) {
     215            0 :       const char = input[i++]
     216              : 
     217            0 :       if (char === '\\') {
     218            0 :         choice += handleEscape()
     219            0 :         continue
     220            0 :       } else if (char === '{') {
     221            0 :         depth++
     222            0 :       } else if (char === '}') {
     223            0 :         if (!depth) break
     224            0 :         depth--
     225            0 :       } else if (char === '|') {
     226            0 :         if (!depth) {
     227            0 :           options.push(choice)
     228            0 :           choice = ''
     229            0 :           continue
     230              :         }
     231              :       }
     232            0 :       choice += char
     233              :     }
     234              : 
     235            0 :     options.push(choice)
     236              : 
     237            0 :     const chosenOption = options[Math.floor(Math.random() * options.length)]
     238            0 :     return processDynamicPrompt(chosenOption)
     239              :   }
     240              : 
     241          250 :   while (i < input.length) {
     242        10652 :     const char = input[i++]
     243        10652 :     if (char === '\\') {
     244            0 :       result += handleEscape()
     245        10652 :     } else if (char === '{') {
     246            0 :       result += parseChoiceBlock()
     247              :     } else {
     248        10652 :       result += char
     249              :     }
     250              :   }
     251              : 
     252          250 :   return result.replace(/\\([{}|])/g, '$1')
     253              : }
     254              : 
     255         2324 : export function isValidUrl(url: string): boolean {
     256         2324 :   try {
     257         2324 :     new URL(url)
     258         2324 :     return true
     259              :   } catch {
     260            0 :     return false
     261              :   }
     262              : }
     263              : 
     264              : export function joinFilePath(
     265              :   subfolder: string | null | undefined,
     266              :   filename: string | null | undefined
     267              : ): string {
     268              :   const normalizedSubfolder = normalizeFilePathSeparators(
     269              :     subfolder ?? ''
     270              :   ).replace(/^\/+|\/+$/g, '')
     271              :   const normalizedFilename = normalizeFilePathSeparators(
     272              :     filename ?? ''
     273              :   ).replace(/^\/+/g, '')
     274              :   if (!normalizedSubfolder) return normalizedFilename
     275              :   if (!normalizedFilename) return normalizedSubfolder
     276              :   return `${normalizedSubfolder}/${normalizedFilename}`
     277              : }
     278              : 
     279              : export function getFilePathSeparatorVariants(filepath: string): string[] {
     280              :   const slashPath = normalizeFilePathSeparators(filepath)
     281              :   const backslashPath = slashPath.replace(/\//g, '\\')
     282              :   return slashPath === backslashPath ? [slashPath] : [slashPath, backslashPath]
     283              : }
     284              : 
     285          353 : function normalizeFilePathSeparators(filepath: string): string {
     286          353 :   return filepath.replace(/[\\/]+/g, '/')
     287              : }
     288              : 
     289              : /**
     290              :  * Parses a filepath into its filename and subfolder components.
     291              :  *
     292              :  * @example
     293              :  * parseFilePath('folder/file.txt')    // → { filename: 'file.txt', subfolder: 'folder' }
     294              :  * parseFilePath('/folder/file.txt')   // → { filename: 'file.txt', subfolder: 'folder' }
     295              :  * parseFilePath('file.txt')           // → { filename: 'file.txt', subfolder: '' }
     296              :  * parseFilePath('folder//file.txt')   // → { filename: 'file.txt', subfolder: 'folder' }
     297              :  *
     298              :  * @param filepath The filepath to parse
     299              :  * @returns Object containing filename and subfolder
     300              :  */
     301          353 : export function parseFilePath(filepath?: string): {
     302              :   filename: string
     303              :   subfolder: string
     304              : } {
     305          353 :   if (!filepath?.trim()) return { filename: '', subfolder: '' }
     306              : 
     307          353 :   const normalizedPath = normalizeFilePathSeparators(filepath)
     308              :     .replace(/^\//, '') // Remove leading slash
     309              :     .replace(/\/$/, '') // Remove trailing slash
     310              : 
     311          353 :   const lastSlashIndex = normalizedPath.lastIndexOf('/')
     312              : 
     313          353 :   if (lastSlashIndex === -1) {
     314          352 :     return {
     315              :       filename: normalizedPath,
     316              :       subfolder: ''
     317              :     }
     318              :   }
     319              : 
     320            1 :   return {
     321              :     filename: normalizedPath.slice(lastSlashIndex + 1),
     322              :     subfolder: normalizedPath.slice(0, lastSlashIndex)
     323              :   }
     324              : }
     325              : 
     326              : // Simple date formatter
     327         2356 : const parts = {
     328              :   d: (d: Date) => d.getDate(),
     329              :   M: (d: Date) => d.getMonth() + 1,
     330              :   h: (d: Date) => d.getHours(),
     331              :   m: (d: Date) => d.getMinutes(),
     332              :   s: (d: Date) => d.getSeconds()
     333              : }
     334         2356 : const format =
     335              :   Object.keys(parts)
     336              :     .map((k) => k + k + '?')
     337              :     .join('|') + '|yyy?y?'
     338              : 
     339            0 : export function formatDate(text: string, date: Date) {
     340            0 :   return text.replace(new RegExp(format, 'g'), (text: string): string => {
     341            0 :     if (text === 'yy') return (date.getFullYear() + '').substring(2)
     342            0 :     if (text === 'yyyy') return date.getFullYear().toString()
     343            0 :     if (text[0] in parts) {
     344              :       const p = parts[text[0] as keyof typeof parts](date)
     345            0 :       return (p + '').padStart(text.length, '0')
     346              :     }
     347            0 :     return text
     348              :   })
     349              : }
     350              : 
     351              : /**
     352              :  * Generate a cache key from parameters
     353              :  * Sorts the parameters to ensure consistent keys regardless of parameter order
     354              :  */
     355         2356 : export const paramsToCacheKey = (params: unknown): string => {
     356          200 :   if (typeof params === 'string') return params
     357          200 :   if (typeof params === 'object' && params !== null)
     358           48 :     return Object.keys(params)
     359              :       .sort((a, b) => a.localeCompare(b))
     360              :       .map((key) => `${key}:${params[key as keyof typeof params]}`)
     361              :       .join('&')
     362              : 
     363            0 :   return String(params)
     364              : }
     365              : 
     366         2356 : const UUID_PATTERN =
     367              :   /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
     368              : 
     369              : /** Accepts canonical UUIDs of any version or variant for legacy compatibility. */
     370         2356 : export const isValidUuid = (value: unknown): value is string =>
     371              :   typeof value === 'string' && UUID_PATTERN.test(value)
     372              : 
     373              : /**
     374              :  * Generates a RFC4122 compliant UUID v4 using the native crypto API when available
     375              :  * @returns A properly formatted UUID string
     376              :  */
     377         2356 : export const generateUUID = (): string => {
     378              :   // Use native crypto.randomUUID() if available (modern browsers)
     379       276123 :   if (
     380              :     typeof crypto !== 'undefined' &&
     381              :     typeof crypto.randomUUID === 'function'
     382              :   ) {
     383       276123 :     return crypto.randomUUID()
     384              :   }
     385              : 
     386              :   // Fallback implementation for older browsers
     387            0 :   return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
     388            0 :     const r = (Math.random() * 16) | 0
     389              :     const v = c === 'x' ? r : (r & 0x3) | 0x8
     390            0 :     return v.toString(16)
     391              :   })
     392              : }
     393              : 
     394         2356 : const isCivitaiHost = (hostname: string): boolean =>
     395              :   hostname === 'civitai.com' ||
     396              :   hostname.endsWith('.civitai.com') ||
     397              :   hostname === 'civitai.red' ||
     398              :   hostname.endsWith('.civitai.red')
     399              : 
     400              : /**
     401              :  * Checks if a URL belongs to any Civitai domain (civitai.com or civitai.red).
     402              :  * Use this for source-name detection; use `isCivitaiModelUrl` when the URL
     403              :  * must also match a specific model API path format.
     404              :  */
     405         2356 : export const isCivitaiUrl = (url: string): boolean => {
     406            0 :   if (!isValidUrl(url)) return false
     407            0 :   return isCivitaiHost(new URL(url).hostname.toLowerCase())
     408              : }
     409              : 
     410              : /**
     411              :  * Checks if a URL is a Civitai model URL
     412              :  * @example
     413              :  * isCivitaiModelUrl('https://civitai.com/api/download/models/1234567890') // true
     414              :  * isCivitaiModelUrl('https://civitai.com/api/v1/models/1234567890') // true
     415              :  * isCivitaiModelUrl('https://civitai.com/api/v1/models-versions/15342') // true
     416              :  * isCivitaiModelUrl('https://example.com/model.safetensors') // false
     417              :  */
     418         2356 : export const isCivitaiModelUrl = (url: string): boolean => {
     419         2324 :   if (!isValidUrl(url)) return false
     420              : 
     421         2324 :   const urlObj = new URL(url)
     422         2324 :   if (!isCivitaiHost(urlObj.hostname.toLowerCase())) return false
     423              : 
     424            0 :   const pathname = urlObj.pathname
     425         2324 :   return (
     426              :     /^\/api\/download\/models\/(\d+)$/.test(pathname) ||
     427              :     /^\/api\/v1\/models\/(\d+)$/.test(pathname) ||
     428              :     /^\/api\/v1\/models-versions\/(\d+)$/.test(pathname)
     429              :   )
     430              : }
     431              : 
     432              : /**
     433              :  * Converts a Hugging Face download URL to a repository page URL
     434              :  * @param url The download URL to convert
     435              :  * @returns The repository page URL or the Hugging Face root if conversion fails
     436              :  * @example
     437              :  * downloadUrlToHfRepoUrl(
     438              :  *  'https://huggingface.co/bfl/FLUX.1/resolve/main/flux1-canny-dev.safetensors?download=true'
     439              :  * ) // https://huggingface.co/bfl/FLUX.1
     440              :  */
     441         2356 : export const downloadUrlToHfRepoUrl = (url: string): string => {
     442            4 :   try {
     443              :     const urlObj = new URL(url)
     444            4 :     const pathname = urlObj.pathname
     445              : 
     446              :     // Use regex to match everything before /resolve/ or /blob/
     447              :     const regex = /^(.*?)(?:\/resolve\/|\/blob\/|$)/
     448              :     const repoPathMatch = regex.exec(pathname)
     449              : 
     450              :     // Extract the repository path and remove leading slash if present
     451              :     const repoPath = repoPathMatch?.[1]?.replace(/^\//, '') || ''
     452              : 
     453              :     return `https://huggingface.co/${repoPath}`
     454              :   } catch {
     455            0 :     return 'https://huggingface.co/'
     456              :   }
     457              : }
     458              : 
     459              : /**
     460              :  * Converts Metronome's integer amount back to a formatted currency string.
     461              :  * For USD, converts from cents to dollars.
     462              :  * For all other currencies (including custom pricing units), returns the amount as is.
     463              :  * This is specific to Metronome's API requirements.
     464              :  *
     465              :  * @param amount - The amount in Metronome's integer format (cents for USD, base units for others)
     466              :  * @param currency - The currency to convert
     467              :  * @returns The formatted amount in currency with 2 decimal places for USD
     468              :  * @example
     469              :  * formatMetronomeCurrency(123, 'usd') // returns "1.23" (cents to USD)
     470              :  * formatMetronomeCurrency(1000, 'jpy') // returns "1000" (yen)
     471              :  */
     472              : export function formatMetronomeCurrency(
     473              :   amount: number,
     474              :   currency: string
     475              : ): string {
     476              :   if (currency === 'usd') {
     477              :     return (amount / 100).toFixed(2)
     478              :   }
     479              :   return amount.toString()
     480              : }
     481              : 
     482              : /**
     483              :  * Converts a USD amount to microdollars (1/1,000,000 of a dollar).
     484              :  * This conversion is commonly used in financial systems to avoid floating-point precision issues
     485              :  * by representing monetary values as integers.
     486              :  *
     487              :  * @param usd - The amount in US dollars to convert
     488              :  * @returns The amount in microdollars (multiplied by 1,000,000)
     489              :  * @example
     490              :  * usdToMicros(1.23) // returns 1230000
     491              :  */
     492              : export function usdToMicros(usd: number): number {
     493              :   return Math.round(usd * 1_000_000)
     494              : }
     495              : 
     496              : /**
     497              :  * Converts URLs in a string to HTML links.
     498              :  * @param text - The string to convert
     499              :  * @returns The string with URLs converted to HTML links
     500              :  * @example
     501              :  * linkifyHtml('Visit https://example.com for more info') // returns 'Visit <a href="https://example.com" target="_blank" rel="noopener noreferrer" class="text-primary hover:underline">https://example.com</a> for more info'
     502              :  */
     503            2 : export function linkifyHtml(text: string): string {
     504            2 :   if (!text) return ''
     505              :   const urlRegex =
     506              :     /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#/%?=~_|!:,.;]*[-A-Z0-9+&@#/%?=~_|])|(\bwww\.[-A-Z0-9+&@#/%?=~_|!:,.;]*[-A-Z0-9+&@#/%?=~_|])/gi
     507            2 :   return text.replace(urlRegex, (_match, p1, _p2, p3) => {
     508            1 :     const url = p1 || p3
     509              :     const href = p3 ? `http://${url}` : url
     510            1 :     return `<a href="${href}" target="_blank" rel="noopener noreferrer" class="text-primary hover:underline">${url}</a>`
     511              :   })
     512              : }
     513              : 
     514              : /**
     515              :  * Converts newline characters to HTML <br> tags.
     516              :  * @param text - The string to convert
     517              :  * @returns The string with newline characters converted to <br> tags
     518              :  * @example
     519              :  * nl2br('Hello\nWorld') // returns 'Hello<br />World'
     520              :  */
     521            2 : export function nl2br(text: string): string {
     522            2 :   if (!text) return ''
     523            2 :   return text.replace(/\n/g, '<br />')
     524              : }
     525              : 
     526              : /**
     527              :  * Converts a version string to an anchor-safe format by replacing dots with dashes.
     528              :  * @param version The version string (e.g., "1.0.0", "2.1.3-beta.1")
     529              :  * @returns The anchor-safe version string (e.g., "v1-0-0", "v2-1-3-beta-1")
     530              :  * @example
     531              :  * formatVersionAnchor("1.0.0") // returns "v1-0-0"
     532              :  * formatVersionAnchor("2.1.3-beta.1") // returns "v2-1-3-beta-1"
     533              :  */
     534            1 : export function formatVersionAnchor(version: string): string {
     535            1 :   return `v${version.replace(/\./g, '-')}`
     536              : }
     537              : 
     538              : /**
     539              :  * Supported locale types for the application (from OpenAPI schema)
     540              :  */
     541              : type SupportedLocale = NonNullable<
     542              :   operations['getReleaseNotes']['parameters']['query']['locale']
     543              : >
     544              : 
     545              : /**
     546              :  * Converts a string to a valid locale type with 'en' as default
     547              :  * @param locale - The locale string to validate and convert
     548              :  * @returns A valid SupportedLocale type, defaults to 'en' if invalid
     549              :  * @example
     550              :  * stringToLocale('fr') // returns 'fr'
     551              :  * stringToLocale('invalid') // returns 'en'
     552              :  * stringToLocale('') // returns 'en'
     553              :  */
     554         4435 : export function stringToLocale(locale: string): SupportedLocale {
     555              :   const supportedLocales: SupportedLocale[] = [
     556              :     'en',
     557              :     'es',
     558              :     'fr',
     559              :     'ja',
     560              :     'ko',
     561              :     'ru',
     562              :     'zh'
     563              :   ]
     564         4435 :   return supportedLocales.includes(locale as SupportedLocale)
     565              :     ? (locale as SupportedLocale)
     566              :     : 'en'
     567              : }
     568              : 
     569            3 : export function formatDuration(milliseconds: number): string {
     570            3 :   if (!milliseconds || milliseconds < 0) return '0s'
     571              : 
     572            3 :   const totalSeconds = Math.floor(milliseconds / 1000)
     573            3 :   const hours = Math.floor(totalSeconds / 3600)
     574            3 :   const minutes = Math.floor((totalSeconds % 3600) / 60)
     575            3 :   const remainingSeconds = Math.floor(totalSeconds % 60)
     576              : 
     577            3 :   const parts: string[] = []
     578              : 
     579            3 :   if (hours > 0) {
     580            0 :     parts.push(`${hours}h`)
     581              :   }
     582            3 :   if (minutes > 0) {
     583            0 :     parts.push(`${minutes}m`)
     584              :   }
     585            3 :   if (remainingSeconds > 0 || parts.length === 0) {
     586            3 :     parts.push(`${remainingSeconds}s`)
     587              :   }
     588              : 
     589            3 :   return parts.join(' ')
     590              : }
     591              : 
     592         2356 : const IMAGE_EXTENSIONS = [
     593              :   'avif',
     594              :   'bmp',
     595              :   'exr',
     596              :   'hdr',
     597              :   'ico',
     598              :   'gif',
     599              :   'jpeg',
     600              :   'jpg',
     601              :   'png',
     602              :   'svg',
     603              :   'tif',
     604              :   'tiff',
     605              :   'webp'
     606              : ] as const
     607         2356 : const VIDEO_EXTENSIONS = ['mp4', 'm4v', 'webm', 'mov', 'avi', 'mkv'] as const
     608         2356 : const AUDIO_EXTENSIONS = ['mp3', 'wav', 'ogg', 'flac', 'opus', 'm4a'] as const
     609         2356 : const THREE_D_EXTENSIONS = [
     610              :   'obj',
     611              :   'fbx',
     612              :   'gltf',
     613              :   'glb',
     614              :   'stl',
     615              :   'usdz',
     616              :   'ply',
     617              :   'spz',
     618              :   'splat',
     619              :   'ksplat'
     620              : ] as const
     621         2356 : const TEXT_EXTENSIONS = [
     622              :   'txt',
     623              :   'md',
     624              :   'markdown',
     625              :   'json',
     626              :   'csv',
     627              :   'yaml',
     628              :   'yml',
     629              :   'xml',
     630              :   'log'
     631              : ] as const
     632              : 
     633              : const MEDIA_TYPES = ['image', 'video', 'audio', '3D', 'text', 'other'] as const
     634              : export type MediaType = (typeof MEDIA_TYPES)[number]
     635              : 
     636              : // Type guard helper for checking array membership
     637              : type ImageExtension = (typeof IMAGE_EXTENSIONS)[number]
     638              : export type VideoExtension = (typeof VIDEO_EXTENSIONS)[number]
     639              : type AudioExtension = (typeof AUDIO_EXTENSIONS)[number]
     640              : type ThreeDExtension = (typeof THREE_D_EXTENSIONS)[number]
     641              : type TextExtension = (typeof TEXT_EXTENSIONS)[number]
     642              : 
     643              : /**
     644              :  * Truncates a filename while preserving the extension
     645              :  * @param filename The filename to truncate
     646              :  * @param maxLength Maximum length for the filename without extension
     647              :  * @returns Truncated filename with extension preserved
     648              :  */
     649            6 : export function truncateFilename(
     650              :   filename: string,
     651              :   maxLength: number = 20
     652              : ): string {
     653            6 :   if (!filename || filename.length <= maxLength) {
     654            6 :     return filename
     655              :   }
     656              : 
     657            0 :   const lastDotIndex = filename.lastIndexOf('.')
     658            6 :   const nameWithoutExt =
     659              :     lastDotIndex > -1 ? filename.substring(0, lastDotIndex) : filename
     660            6 :   const extension = lastDotIndex > -1 ? filename.substring(lastDotIndex) : ''
     661              : 
     662              :   // If the name without extension is short enough, return as is
     663            6 :   if (nameWithoutExt.length <= maxLength) {
     664            0 :     return filename
     665              :   }
     666              : 
     667              :   // Calculate how to split the truncation
     668            0 :   const halfLength = Math.floor((maxLength - 3) / 2) // -3 for '...'
     669              :   const start = nameWithoutExt.substring(0, halfLength)
     670              :   const end = nameWithoutExt.substring(nameWithoutExt.length - halfLength)
     671              : 
     672            0 :   return `${start}...${end}${extension}`
     673              : }
     674              : 
     675              : /**
     676              :  * Determines the media type from a filename's extension (singular form)
     677              :  * @param filename The filename to analyze
     678              :  * @returns The media type: 'image', 'video', 'audio', '3D', 'text', or 'other'
     679              :  */
     680        44359 : export function getMediaTypeFromFilename(
     681              :   filename: string | null | undefined
     682              : ): MediaType {
     683        44359 :   if (!filename) return 'other'
     684        44359 :   const ext = filename.split('.').pop()?.toLowerCase()
     685        44359 :   if (!ext) return 'other'
     686              : 
     687              :   // Type-safe array includes check using type assertion
     688        38756 :   if (IMAGE_EXTENSIONS.includes(ext as ImageExtension)) return 'image'
     689        20756 :   if (VIDEO_EXTENSIONS.includes(ext as VideoExtension)) return 'video'
     690        13276 :   if (AUDIO_EXTENSIONS.includes(ext as AudioExtension)) return 'audio'
     691         6437 :   if (THREE_D_EXTENSIONS.includes(ext as ThreeDExtension)) return '3D'
     692          675 :   if (TEXT_EXTENSIONS.includes(ext as TextExtension)) return 'text'
     693              : 
     694           65 :   return 'other'
     695              : }
     696              : 
     697          835 : export function isPreviewableMediaType(mediaType: MediaType): boolean {
     698          835 :   return mediaType !== 'other'
     699              : }
     700              : 
     701           44 : export function formatTime(seconds: number): string {
     702           44 :   if (isNaN(seconds) || seconds === 0) return '0:00'
     703              :   const mins = Math.floor(seconds / 60)
     704              :   const secs = Math.floor(seconds % 60)
     705           10 :   return `${mins}:${secs.toString().padStart(2, '0')}`
     706              : }
     707              : 
     708              : /**
     709              :  * Format a number with the given BCP-47 locale.
     710              :  * Returns an em-dash for non-numeric, NaN, or infinite inputs.
     711              :  */
     712              : export function formatLocalizedNumber(
     713              :   value: number | undefined,
     714              :   locale: string
     715              : ): string {
     716              :   if (typeof value !== 'number' || !Number.isFinite(value)) return '—'
     717              :   return new Intl.NumberFormat(locale).format(value)
     718              : }
     719              : 
     720              : /**
     721              :  * Format an ISO 8601 date string with the given BCP-47 locale using the
     722              :  * `medium` date style (e.g. "Apr 19, 2026"). Returns an em-dash for missing
     723              :  * or unparseable inputs.
     724              :  */
     725              : export function formatLocalizedMediumDate(
     726              :   value: string | undefined,
     727              :   locale: string
     728              : ): string {
     729              :   if (!value) return '—'
     730              :   const timestamp = Date.parse(value)
     731              :   if (Number.isNaN(timestamp)) return '—'
     732              :   return new Intl.DateTimeFormat(locale, { dateStyle: 'medium' }).format(
     733              :     timestamp
     734              :   )
     735              : }
        

Generated by: LCOV version 2.0-1