LCOV - code coverage report
Current view: top level - src - i18n.ts Coverage Total Hit
Test: ComfyUI E2E Coverage Lines: 82.0 % 122 100
Test Date: 2026-11-17 04:17:53

            Line data    Source code
       1              : import { createI18n } from 'vue-i18n'
       2              : import type { PluralizationRule } from 'vue-i18n'
       3              : 
       4              : import {
       5              :   getDefaultLocale,
       6              :   localeDefinitions,
       7              :   resolveSupportedLocale
       8              : } from '@/locales/localeConfig'
       9              : import type { SupportedLocale } from '@/locales/localeConfig'
      10              : import { RUSSIAN_PLURAL_FORM_COUNT } from '@/i18nPluralForms'
      11              : import { normalizeI18nKey } from '@/utils/formatUtil'
      12              : 
      13              : import enCommands from './locales/en/commands.json' with { type: 'json' }
      14              : import en from './locales/en/main.json' with { type: 'json' }
      15              : import enNodes from './locales/en/nodeDefs.json' with { type: 'json' }
      16              : import enSettings from './locales/en/settings.json' with { type: 'json' }
      17              : 
      18              : export { resolveSupportedLocale }
      19              : 
      20         2364 : function buildLocale<
      21              :   M extends Record<string, unknown>,
      22              :   N extends Record<string, unknown>,
      23              :   C extends Record<string, unknown>,
      24              :   S extends Record<string, unknown>
      25              : >(main: M, nodes: N, commands: C, settings: S) {
      26         2364 :   return {
      27              :     ...main,
      28              :     nodeDefs: nodes,
      29              :     commands: commands,
      30              :     settings: settings
      31              :   } as M & { nodeDefs: N; commands: C; settings: S }
      32              : }
      33              : 
      34              : // Track which locales have been loaded
      35         2356 : const loadedLocales = new Set<string>(['en'])
      36              : 
      37              : // Track locales currently being loaded to prevent race conditions
      38         2356 : const loadingLocales = new Map<string, Promise<void>>()
      39              : 
      40              : // Store custom nodes i18n data for merging when locales are lazily loaded
      41         2356 : const customNodesI18nData: Record<string, unknown> = {}
      42              : 
      43              : /**
      44              :  * Dynamically load a shipped locale's bundles (nodeDefs, commands, settings).
      45              :  * Callers must pre-resolve untrusted input via `resolveSupportedLocale` or
      46              :  * `setActiveLocale`, which is the boundary helper for arbitrary input.
      47              :  */
      48         2362 : export async function loadLocale(locale: SupportedLocale): Promise<void> {
      49         2362 :   if (loadedLocales.has(locale)) {
      50         2354 :     return
      51              :   }
      52              : 
      53            8 :   const existingLoad = loadingLocales.get(locale)
      54          593 :   if (existingLoad) {
      55            0 :     await existingLoad
      56            0 :     return
      57              :   }
      58              : 
      59            8 :   const loaders = localeDefinitions[locale].loaders
      60           14 :   if (!loaders) {
      61            0 :     return
      62              :   }
      63              : 
      64            8 :   const loadPromise = (async () => {
      65            8 :     try {
      66            8 :       const [main, nodes, commands, settings] = await Promise.all([
      67              :         loaders.main(),
      68              :         loaders.nodeDefs(),
      69              :         loaders.commands(),
      70              :         loaders.settings()
      71              :       ])
      72              : 
      73            8 :       const messages = buildLocale(
      74              :         main.default,
      75              :         nodes.default,
      76              :         commands.default,
      77              :         settings.default
      78              :       )
      79              : 
      80            8 :       i18n.global.setLocaleMessage(locale, messages as LocaleMessages)
      81            8 :       loadedLocales.add(locale)
      82              : 
      83            8 :       if (customNodesI18nData[locale]) {
      84            2 :         i18n.global.mergeLocaleMessage(locale, customNodesI18nData[locale])
      85              :       }
      86              :     } catch (error) {
      87            0 :       console.error(`Failed to load locale "${locale}":`, error)
      88            0 :       throw error
      89              :     } finally {
      90            8 :       loadingLocales.delete(locale)
      91              :     }
      92              :   })()
      93              : 
      94            8 :   loadingLocales.set(locale, loadPromise)
      95            8 :   await loadPromise
      96              : }
      97              : 
      98              : /**
      99              :  * Boundary helper for arbitrary locale input (settings, browser preferences):
     100              :  * resolves to a shipped tag, loads it, and updates the active locale.
     101              :  *
     102              :  * Returns the resolved tag so callers can detect a clamp (e.g. a stale stored
     103              :  * `Comfy.Locale` from an older build) and self-heal persisted state.
     104              :  */
     105         2362 : export async function setActiveLocale(
     106              :   input: string | readonly string[] | null | undefined
     107              : ): Promise<SupportedLocale> {
     108         2362 :   const resolved = resolveSupportedLocale(input)
     109         2362 :   if (typeof input === 'string' && input && input !== resolved) {
     110              :     // Single warn — gated on a real clamp event, never per missing key — so
     111              :     // stale stored locales surface in logs without re-introducing #1867's spam.
     112            1 :     console.warn(`Locale "${input}" not shipped; using "${resolved}"`)
     113              :   }
     114         2362 :   await loadLocale(resolved)
     115         2362 :   i18n.global.locale.value = resolved
     116         2362 :   return resolved
     117              : }
     118              : 
     119              : /**
     120              :  * Stores the data for later use when locales are lazily loaded,
     121              :  * and immediately merges data for already-loaded locales.
     122              :  */
     123         2355 : export function mergeCustomNodesI18n(i18nData: Record<string, unknown>): void {
     124              :   // Clear existing data and replace with new data
     125         2355 :   for (const key of Object.keys(customNodesI18nData)) {
     126            0 :     delete customNodesI18nData[key]
     127              :   }
     128         2355 :   Object.assign(customNodesI18nData, i18nData)
     129              : 
     130         2355 :   for (const [locale, message] of Object.entries(i18nData)) {
     131            4 :     if (loadedLocales.has(locale)) {
     132            1 :       i18n.global.mergeLocaleMessage(locale, message)
     133              :     }
     134              :   }
     135              : }
     136              : 
     137              : export type NodeDefTextField = 'display_name' | 'description'
     138              : 
     139              : /**
     140              :  * Raw `/object_info` text, kept out of the vue-i18n message tree so English
     141              :  * never reaches the message compiler. Rebuilt on every fetch, so a def that
     142              :  * stops sending a field stops resolving to the previous value.
     143              :  */
     144         2356 : const backendNodeText = new Map<
     145              :   string,
     146              :   Partial<Record<NodeDefTextField, string>>
     147              : >()
     148              : 
     149         2378 : export function setBackendNodeText(
     150              :   defs: Iterable<{
     151              :     name?: unknown
     152              :     display_name?: unknown
     153              :     description?: unknown
     154              :   }>
     155              : ): void {
     156         2378 :   backendNodeText.clear()
     157         2378 :   for (const def of defs) {
     158      2446581 :     if (typeof def.name !== 'string') continue
     159      2446581 :     const entry: Partial<Record<NodeDefTextField, string>> = {}
     160      2446581 :     if (typeof def.display_name === 'string' && def.display_name) {
     161      2100123 :       entry.display_name = def.display_name
     162              :     }
     163      2446581 :     if (typeof def.description === 'string' && def.description) {
     164      1314651 :       entry.description = def.description
     165              :     }
     166      2446581 :     if (entry.display_name ?? entry.description)
     167      2133345 :       backendNodeText.set(def.name, entry)
     168              :   }
     169              : }
     170              : 
     171     12488525 : function customNodesProvide(nodeName: string, path: string): boolean {
     172     12488525 :   const data = customNodesI18nData[i18n.global.locale.value]
     173     12488525 :   if (typeof data !== 'object' || data === null) return false
     174        10112 :   const nodeDefs = (data as Record<string, unknown>)['nodeDefs']
     175     12488525 :   if (typeof nodeDefs !== 'object' || nodeDefs === null) return false
     176              : 
     177        10112 :   for (const candidate of nodeDefKeyCandidates(nodeName)) {
     178        10132 :     let cursor: unknown = nodeDefs
     179        10132 :     for (const segment of `${candidate}.${path}`.split('.')) {
     180        20270 :       if (typeof cursor !== 'object' || cursor === null) {
     181        10122 :         cursor = undefined
     182        10122 :         break
     183              :       }
     184        10148 :       cursor = (cursor as Record<string, unknown>)[segment]
     185              :     }
     186        10132 :     if (typeof cursor === 'string') return true
     187              :   }
     188        10102 :   return false
     189              : }
     190              : 
     191              : /**
     192              :  * Generated locales key dotted node ids flat (`my_node`). Locales written by
     193              :  * hand before that convention nest them (`my.node`), which vue-i18n resolves by
     194              :  * path traversal, so both are tried.
     195              :  */
     196      1857733 : function nodeDefKeyCandidates(nodeName: string): string[] {
     197      1857733 :   const normalized = normalizeI18nKey(nodeName)
     198      1857733 :   return normalized === nodeName ? [normalized] : [normalized, nodeName]
     199              : }
     200              : 
     201              : /**
     202              :  * Reads a resolved locale message. `st` compiles it; `stRaw` does not.
     203              :  */
     204              : type MessageReader = (key: string, fallbackMessage: string) => string
     205              : 
     206      1847621 : function translateNodeDefText(
     207              :   nodeName: string,
     208              :   path: string,
     209              :   fallback: string,
     210              :   read: MessageReader
     211              : ): string {
     212      1847621 :   for (const candidate of nodeDefKeyCandidates(nodeName)) {
     213      1848121 :     const key = `nodeDefs.${candidate}.${path}`
     214      1848121 :     if (te(key)) return read(key, fallback)
     215              :   }
     216        13935 :   return fallback
     217              : }
     218              : 
     219              : /**
     220              :  * Resolves node text in priority order.
     221              :  *
     222              :  * `en`: custom-node `/api/i18n` translations, then the live backend value, then
     223              :  * the bundled snapshot. English is the source language, so a backend value is
     224              :  * data rather than a translation and is returned without being compiled.
     225              :  *
     226              :  * Other locales: translations stay authoritative, falling back to the live
     227              :  * backend value rather than the stale English snapshot.
     228              :  */
     229     12488525 : function resolveNodeDefPath(
     230              :   nodeName: string,
     231              :   path: string,
     232              :   backend: string | undefined,
     233              :   fallback: string,
     234              :   read: MessageReader
     235              : ): string {
     236     12488525 :   if (customNodesProvide(nodeName, path)) {
     237           10 :     return translateNodeDefText(nodeName, path, fallback, read)
     238              :   }
     239     12488525 :   if (i18n.global.locale.value === 'en' && backend !== undefined) return backend
     240              : 
     241      1847611 :   return translateNodeDefText(nodeName, path, fallback, read)
     242              : }
     243              : 
     244     12367024 : export function resolveNodeDefText(
     245              :   field: NodeDefTextField,
     246              :   nodeName: string,
     247              :   backendValue?: string
     248              : ): string {
     249     12367024 :   const backend = backendValue ?? backendNodeText.get(nodeName)?.[field]
     250              :   const fallback = backend ?? (field === 'display_name' ? nodeName : '')
     251              : 
     252     12367024 :   return resolveNodeDefPath(nodeName, field, backend, fallback, st)
     253              : }
     254              : 
     255              : /** Slot fields the generated locales carry text for. */
     256              : export type NodeDefSlotTextField = 'name' | 'tooltip'
     257              : 
     258              : /**
     259              :  * `name` is escaped by `scripts/nodeDefLocaleSerializer.ts` and has to be
     260              :  * compiled back; `tooltip` is stored verbatim and must never reach the message
     261              :  * compiler, or a literal `{'@'}` would render to the user.
     262              :  */
     263       121501 : function slotMessageReader(field: NodeDefSlotTextField): MessageReader {
     264       121501 :   return field === 'tooltip' ? stRaw : st
     265              : }
     266              : 
     267       121501 : export function resolveNodeDefSlotText(
     268              :   field: NodeDefSlotTextField,
     269              :   nodeName: string,
     270              :   slot: string | number,
     271              :   backendValue?: string,
     272              :   fallbackValue = ''
     273              : ): string {
     274              :   const slotPath =
     275              :     typeof slot === 'string'
     276              :       ? `inputs.${normalizeI18nKey(slot)}`
     277              :       : `outputs.${slot}`
     278              : 
     279       121501 :   return resolveNodeDefPath(
     280              :     nodeName,
     281              :     `${slotPath}.${field}`,
     282              :     backendValue,
     283              :     backendValue ?? fallbackValue,
     284              :     slotMessageReader(field)
     285              :   )
     286              : }
     287              : 
     288              : type LocaleMessages = typeof en & {
     289              :   nodeDefs: typeof enNodes
     290              :   commands: typeof enCommands
     291              :   settings: typeof enSettings
     292              : }
     293              : 
     294              : export const FALLBACK_LOCALE = 'en'
     295              : 
     296         2356 : const russianPluralRules = new Intl.PluralRules('ru')
     297              : 
     298         2356 : const russianPluralRule: PluralizationRule = (
     299              :   choice,
     300              :   choicesLength,
     301              :   defaultRule
     302              : ) => {
     303            0 :   if (choicesLength !== RUSSIAN_PLURAL_FORM_COUNT) {
     304            0 :     return defaultRule ? defaultRule(choice, choicesLength) : 0
     305              :   }
     306              : 
     307            0 :   switch (russianPluralRules.select(choice)) {
     308              :     case 'one':
     309            0 :       return 0
     310              :     case 'few':
     311            0 :       return 1
     312              :     case 'many':
     313            0 :       return 2
     314              :     default:
     315            0 :       return 3
     316              :   }
     317              : }
     318              : 
     319         2356 : function createAppI18n() {
     320         2356 :   const messages: Partial<Record<SupportedLocale, LocaleMessages>> = {
     321              :     en: buildLocale(en, enNodes, enCommands, enSettings)
     322              :   }
     323         2356 :   return createI18n({
     324              :     legacy: false,
     325              :     locale: getDefaultLocale(),
     326              :     fallbackLocale: FALLBACK_LOCALE,
     327              :     escapeParameter: true,
     328              :     pluralRules: { ru: russianPluralRule },
     329              :     messages,
     330              :     missingWarn: /^(?!settings\.Comfy_Locale\.options\.).+/,
     331              :     fallbackWarn: /^(?!settings\.Comfy_Locale\.options\.).+/
     332              :   })
     333              : }
     334              : 
     335              : type AppI18n = ReturnType<typeof createAppI18n>
     336              : type AppComposer = AppI18n['global']
     337              : 
     338         2356 : let appI18n: AppI18n | undefined
     339              : 
     340     52261704 : function appI18nInstance(): AppI18n {
     341     52261704 :   return (appI18n ??= createAppI18n())
     342              : }
     343              : 
     344              : /** The app's i18n plugin, created on first use rather than at import. */
     345         2356 : export const i18n: AppI18n = {
     346              :   get mode() {
     347            0 :     return appI18nInstance().mode
     348              :   },
     349              :   get global() {
     350     52259349 :     return appI18nInstance().global
     351              :   },
     352              :   install: (app, ...options) => appI18nInstance().install(app, ...options),
     353              :   dispose: () => appI18nInstance().dispose()
     354              : }
     355              : 
     356         2356 : export const t: AppComposer['t'] = (...args: unknown[]): string =>
     357              :   Reflect.apply(i18n.global.t, undefined, args)
     358         2356 : export const te: AppComposer['te'] = (key, locale) =>
     359              :   i18n.global.te(key, locale ?? i18n.global.locale.value)
     360         2356 : export const d: AppComposer['d'] = (...args: unknown[]): string =>
     361              :   Reflect.apply(i18n.global.d, undefined, args)
     362         2356 : const tm: AppComposer['tm'] = (key) => i18n.global.tm(key)
     363              : 
     364            0 : function rawTranslationOrFallback(key: string, fallbackMessage: string) {
     365            0 :   const message = tm(key)
     366            0 :   return typeof message === 'string' ? message : fallbackMessage
     367              : }
     368              : 
     369              : /**
     370              :  * Safe translation function that returns the fallback message if the key is not found.
     371              :  * Invalid message syntax falls back to the raw locale message instead of crashing.
     372              :  *
     373              :  * @param key - The key to translate.
     374              :  * @param fallbackMessage - The fallback message to use if the key is not found.
     375              :  */
     376      7871632 : export function st(key: string, fallbackMessage: string) {
     377      7871632 :   if (!te(key)) return fallbackMessage
     378              : 
     379      7871632 :   try {
     380              :     // The normal defaultMsg overload fails in some cases for custom nodes
     381      7770728 :     return t(key)
     382              :   } catch (error) {
     383            0 :     if (!(error instanceof SyntaxError)) throw error
     384            0 :     return rawTranslationOrFallback(key, fallbackMessage)
     385              :   }
     386              : }
     387              : 
     388              : /**
     389              :  * Safe raw translation function for strings that may contain i18n syntax.
     390              :  *
     391              :  * @param key - The key for the raw locale message.
     392              :  * @param fallbackMessage - The fallback message to use if the key is not found
     393              :  * or the locale message is not a string.
     394              :  */
     395            0 : export function stRaw(key: string, fallbackMessage: string) {
     396            0 :   if (!te(key)) return fallbackMessage
     397              : 
     398            0 :   return rawTranslationOrFallback(key, fallbackMessage)
     399              : }
        

Generated by: LCOV version 2.0-1