{"version":3,"file":"I18nStore.cjs","names":["getReactI18nCache","subscribeToSet","lookupTranslation","lookupDictionaryEntry","lookupDictionaryObject"],"sources":["../../src/i18n-store/I18nStore.ts"],"sourcesContent":["import {\n  createDiagnosticMessage,\n  formatDiagnosticErrorDetails,\n} from 'generaltranslation/internal';\nimport { getTranslateListenerKey } from 'gt-i18n/internal';\nimport type {\n  DictionaryEntrySnapshot,\n  DictionaryLookup,\n  DictionaryObjectSnapshot,\n  StoreListener,\n  TranslateEventListener,\n  TranslateLookup,\n  TranslateSnapshot,\n  Unsubscribe,\n} from './storeTypes';\nimport type { Dictionary, Translation } from 'gt-i18n/types';\nimport { subscribeToSet } from './utils/subscriptions';\nimport { Hash, Locale } from 'gt-i18n/internal/types';\nimport { getReactI18nCache } from '../i18n-cache/singleton-operations';\nimport { lookupTranslation } from './utils/translations';\nimport {\n  lookupDictionaryEntry,\n  lookupDictionaryObject,\n} from './utils/dictionaries';\n\nexport type DictionaryStoreListener = (event: DictionaryLookup) => void;\n\nconst MAX_LOGGED_RUNTIME_TRANSLATION_ERRORS = 100;\n\nfunction getRuntimeTranslationErrorDedupeKey(error: unknown): string {\n  if (error instanceof Error) {\n    return `${error.name}|${error.message}`;\n  }\n  if (error !== null && typeof error === 'object') {\n    try {\n      return `object|${JSON.stringify(error)}`;\n    } catch {\n      return `object|${String(error)}`;\n    }\n  }\n  return `${typeof error}|${String(error)}`;\n}\n\n/**\n * I18nStore gives us the ability to perform client-side updates to translations.\n * Primarily useful for dev hot reload.\n *\n * This is the stateful primitive behind lookup subscriptions and runtime\n * translation requests. It intentionally does not know whether lookups are\n * being served from SPA singletons or SRA provider snapshots; that policy lives\n * in LookupAdapter, not in this store.\n */\nexport class I18nStore {\n  // ----- Listener Sets ----- //\n\n  private translateListeners = new Set<TranslateEventListener>();\n  private dictionaryEntryListeners = new Set<DictionaryStoreListener>();\n  private dictionaryObjectListeners = new Set<DictionaryStoreListener>();\n  private loggedRuntimeTranslationErrors = new Set<string>();\n\n  /**\n   * I18nCache must be already initialized\n   */\n  constructor() {}\n\n  // ========== Translation Updates ========== //\n\n  updateTranslations = (\n    translations: Record<Locale, Record<Hash, Translation>>\n  ): void => {\n    getReactI18nCache().updateTranslations(translations);\n  };\n\n  updateDictionaries = (dictionaries: Record<Locale, Dictionary>): void => {\n    getReactI18nCache().updateDictionaries(dictionaries);\n  };\n\n  // ========== runtime translation ========== //\n\n  translate = async <T extends Translation>(\n    lookup: TranslateLookup<T>\n  ): Promise<void> => {\n    return getReactI18nCache()\n      .lookupTranslationWithFallback(\n        lookup.locale,\n        lookup.message,\n        lookup.options\n      )\n      .then(() => {\n        this.emitTranslateEvent(lookup);\n      })\n      .catch((error) => this.logRuntimeTranslationError(error));\n  };\n\n  translateDictionaryEntry = (lookup: DictionaryLookup): void => {\n    getReactI18nCache()\n      .lookupDictionaryWithFallback(lookup.locale, lookup.id)\n      .then(() => {\n        this.emitDictionaryEvent(lookup);\n      })\n      .catch((error) => this.logRuntimeTranslationError(error));\n  };\n\n  translateDictionaryObject = (lookup: DictionaryLookup): void => {\n    getReactI18nCache()\n      .lookupDictionaryObjWithFallback(lookup.locale, lookup.id)\n      .then(() => {\n        this.emitDictionaryEvent(lookup);\n      })\n      .catch((error) => this.logRuntimeTranslationError(error));\n  };\n\n  /**\n   * Runtime translation runs fire-and-forget, so a rejected request (for\n   * example a 401 from an invalid dev API key) is logged here instead of\n   * escaping as an unhandled rejection that kills the dev server during SSR.\n   * Identical failures log once.\n   */\n  private logRuntimeTranslationError(error: unknown): void {\n    const details = formatDiagnosticErrorDetails(error);\n    const dedupeKey = getRuntimeTranslationErrorDedupeKey(error);\n    if (this.loggedRuntimeTranslationErrors.has(dedupeKey)) return;\n    this.loggedRuntimeTranslationErrors.add(dedupeKey);\n    if (\n      this.loggedRuntimeTranslationErrors.size >\n      MAX_LOGGED_RUNTIME_TRANSLATION_ERRORS\n    ) {\n      const oldest = this.loggedRuntimeTranslationErrors.values().next().value;\n      if (oldest !== undefined) {\n        this.loggedRuntimeTranslationErrors.delete(oldest);\n      }\n    }\n    console.error(\n      createDiagnosticMessage({\n        source: '@generaltranslation/react-core',\n        severity: 'Error',\n        whatHappened: 'A runtime translation request failed.',\n        wayOut: 'Rendering falls back to untranslated content.',\n        details,\n      })\n    );\n  }\n\n  // ========== UseSyncExternalStore ========== //\n\n  // ----- Subscriptions ----- //\n\n  // Keep subscription methods as arrow fields so hooks can pass them by\n  // reference without losing access to this store instance.\n  subscribeToTranslate = <T extends Translation>(\n    lookup: TranslateLookup<T>,\n    listener: StoreListener\n  ): Unsubscribe => {\n    const lookupKey = getTranslateListenerKey(lookup);\n    const wrappedListener: TranslateEventListener = (lookup) => {\n      if (getTranslateListenerKey(lookup) === lookupKey) {\n        listener();\n      }\n    };\n    return subscribeToSet(this.translateListeners, wrappedListener);\n  };\n\n  subscribeToTranslationEvents = (\n    listener: TranslateEventListener\n  ): Unsubscribe => {\n    return subscribeToSet(this.translateListeners, listener);\n  };\n\n  subscribeToDictionaryEntryEvents = (\n    listener: DictionaryStoreListener\n  ): Unsubscribe => {\n    return subscribeToSet(this.dictionaryEntryListeners, listener);\n  };\n\n  subscribeToDictionaryObjectEvents = (\n    listener: DictionaryStoreListener\n  ): Unsubscribe => {\n    return subscribeToSet(this.dictionaryObjectListeners, listener);\n  };\n\n  // ----- Snapshots ----- //\n\n  getTranslateSnapshot = <T extends Translation>(\n    lookup: TranslateLookup<T>,\n    translationsSnapshot: Record<Locale, Record<Hash, Translation>> = {}\n  ): TranslateSnapshot<T> => {\n    return (\n      lookupTranslation(translationsSnapshot, lookup) ??\n      getReactI18nCache().lookupTranslation<T>(\n        lookup.locale,\n        lookup.message,\n        lookup.options\n      )\n    );\n  };\n\n  getDictionaryEntrySnapshot = (\n    lookup: DictionaryLookup,\n    dictionariesSnapshot: Record<Locale, Dictionary> = {}\n  ): DictionaryEntrySnapshot => {\n    return (\n      lookupDictionaryEntry(dictionariesSnapshot, lookup) ??\n      getReactI18nCache().lookupDictionary(lookup.locale, lookup.id)\n    );\n  };\n\n  getDictionaryObjectSnapshot = (\n    lookup: DictionaryLookup,\n    dictionariesSnapshot: Record<Locale, Dictionary> = {}\n  ): DictionaryObjectSnapshot => {\n    return (\n      lookupDictionaryObject(dictionariesSnapshot, lookup) ??\n      getReactI18nCache().lookupDictionaryObj(lookup.locale, lookup.id)\n    );\n  };\n\n  // ----- Listener Utilities ----- //\n\n  private emitTranslateEvent(event: TranslateLookup): void {\n    this.translateListeners.forEach((listener) => listener(event));\n  }\n\n  private emitDictionaryEvent(event: DictionaryLookup): void {\n    this.dictionaryEntryListeners.forEach((listener) => listener(event));\n    this.dictionaryObjectListeners.forEach((listener) => {\n      listener(event);\n    });\n  }\n}\n"],"mappings":"qSA6BA,SAAS,EAAoC,EAAwB,CACnE,GAAI,aAAiB,MACnB,MAAO,GAAG,EAAM,KAAK,GAAG,EAAM,UAEhC,GAAsB,OAAO,GAAU,UAAnC,EACF,GAAI,CACF,MAAO,UAAU,KAAK,UAAU,EAAM,QAChC,CACN,MAAO,UAAU,OAAO,EAAM,GAGlC,MAAO,GAAG,OAAO,EAAM,GAAG,OAAO,EAAM,GAYzC,IAAa,EAAb,KAAuB,CAGrB,mBAA6B,IAAI,IACjC,yBAAmC,IAAI,IACvC,0BAAoC,IAAI,IACxC,+BAAyC,IAAI,IAK7C,aAAc,EAId,mBACE,GACS,CACT,EAAA,mBAAmB,CAAC,mBAAmB,EAAa,EAGtD,mBAAsB,GAAmD,CACvE,EAAA,mBAAmB,CAAC,mBAAmB,EAAa,EAKtD,UAAY,KACV,IAEOA,EAAAA,mBAAmB,CACvB,8BACC,EAAO,OACP,EAAO,QACP,EAAO,QACR,CACA,SAAW,CACV,KAAK,mBAAmB,EAAO,EAC/B,CACD,MAAO,GAAU,KAAK,2BAA2B,EAAM,CAAC,CAG7D,yBAA4B,GAAmC,CAC7D,EAAA,mBAAmB,CAChB,6BAA6B,EAAO,OAAQ,EAAO,GAAG,CACtD,SAAW,CACV,KAAK,oBAA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