@tolgee/core
Advanced tools
Comparing version 5.20.3 to 5.20.4-prerelease.afe383ff.0
@@ -16,2 +16,21 @@ 'use strict'; | ||
} | ||
function handleRegularOrAsyncErr(onError, createError, callback) { | ||
function handle(e) { | ||
const error = createError(e); | ||
onError.emit(error); | ||
// eslint-disable-next-line no-console | ||
console.error(error); | ||
throw error; | ||
} | ||
try { | ||
const result = callback(); | ||
if (isPromise(result)) { | ||
return result.catch(handle); | ||
} | ||
return result; | ||
} | ||
catch (e) { | ||
handle(e); | ||
} | ||
} | ||
function missingOptionError(option) { | ||
@@ -191,2 +210,3 @@ const options = (Array.isArray(option) ? option : [option]).map((val) => `'${val}'`); | ||
onPermanentChange: EventEmitter(isActive), | ||
onError: EventEmitter(isActive), | ||
setEmitterActive(active) { | ||
@@ -215,2 +235,4 @@ emitterActive = active; | ||
return self.onPermanentChange.listen(handler); | ||
case 'error': | ||
return self.onError.listen(handler); | ||
} | ||
@@ -225,2 +247,28 @@ }), | ||
class RecordFetchError extends Error { | ||
constructor(descriptor, cause, isDev = false) { | ||
const { language, namespace } = descriptor; | ||
super(`Tolgee: Failed to fetch record for "${language}"${namespace && ` and "${namespace}"`}`); | ||
this.cause = cause; | ||
this.isDev = isDev; | ||
this.name = 'RecordFetchError'; | ||
this.language = language; | ||
this.namespace = namespace; | ||
} | ||
} | ||
class LanguageDetectorError extends Error { | ||
constructor(message, cause) { | ||
super(message); | ||
this.cause = cause; | ||
this.name = 'LanguageDetectorError'; | ||
} | ||
} | ||
class LanguageStorageError extends Error { | ||
constructor(message, cause) { | ||
super(message); | ||
this.cause = cause; | ||
this.name = 'LanguageStorageError'; | ||
} | ||
} | ||
const flattenTranslations = (data) => { | ||
@@ -258,3 +306,3 @@ const result = new Map(); | ||
function Cache(onCacheChange, backendGetRecord, backendGetDevRecord, withDefaultNs, isInitialLoading, fetchingObserver, loadingObserver) { | ||
function Cache(events, backendGetRecord, backendGetDevRecord, withDefaultNs, isInitialLoading, fetchingObserver, loadingObserver) { | ||
const asyncRequests = new Map(); | ||
@@ -270,3 +318,3 @@ const cache = new Map(); | ||
}); | ||
onCacheChange.emit(descriptor); | ||
events.onCacheChange.emit(descriptor); | ||
} | ||
@@ -277,21 +325,34 @@ /** | ||
function fetchProd(keyObject) { | ||
let dataPromise = undefined; | ||
if (!dataPromise) { | ||
let dataOrPromise = undefined; | ||
if (!dataOrPromise) { | ||
const staticDataValue = staticData[encodeCacheKey(keyObject)]; | ||
if (typeof staticDataValue === 'function') { | ||
dataPromise = staticDataValue(); | ||
dataOrPromise = staticDataValue(); | ||
} | ||
} | ||
if (!dataPromise) { | ||
dataPromise = backendGetRecord(keyObject); | ||
if (!dataOrPromise) { | ||
dataOrPromise = backendGetRecord(keyObject); | ||
} | ||
return dataPromise; | ||
if (isPromise(dataOrPromise)) { | ||
return dataOrPromise === null || dataOrPromise === void 0 ? void 0 : dataOrPromise.catch((e) => { | ||
const error = new RecordFetchError(keyObject, e); | ||
events.onError.emit(error); | ||
// eslint-disable-next-line no-console | ||
console.error(error); | ||
throw error; | ||
}); | ||
} | ||
else { | ||
return dataOrPromise; | ||
} | ||
} | ||
function fetchData(keyObject, isDev) { | ||
var _a; | ||
let dataPromise = undefined; | ||
let dataOrPromise = undefined; | ||
if (isDev) { | ||
dataPromise = (_a = backendGetDevRecord(keyObject)) === null || _a === void 0 ? void 0 : _a.catch(() => { | ||
dataOrPromise = (_a = backendGetDevRecord(keyObject)) === null || _a === void 0 ? void 0 : _a.catch((e) => { | ||
const error = new RecordFetchError(keyObject, e, true); | ||
events.onError.emit(error); | ||
// eslint-disable-next-line no-console | ||
console.warn(`Tolgee: Failed to fetch data from dev backend`); | ||
console.warn(error); | ||
// fallback to prod fetch if dev fails | ||
@@ -301,6 +362,6 @@ return fetchProd(keyObject); | ||
} | ||
if (!dataPromise) { | ||
dataPromise = fetchProd(keyObject); | ||
if (!dataOrPromise) { | ||
dataOrPromise = fetchProd(keyObject); | ||
} | ||
return dataPromise; | ||
return dataOrPromise; | ||
} | ||
@@ -374,3 +435,3 @@ const self = Object.freeze({ | ||
record === null || record === void 0 ? void 0 : record.set(key, value); | ||
onCacheChange.emit(Object.assign(Object.assign({}, descriptor), { key })); | ||
events.onCacheChange.emit(Object.assign(Object.assign({}, descriptor), { key })); | ||
}, | ||
@@ -535,3 +596,3 @@ isFetching(ns) { | ||
function Plugins(getLanguage, getInitialOptions, getAvailableLanguages, getFallbackNamespaces, getTranslationNs, getTranslation, changeTranslation, onPermanentChange) { | ||
function Plugins(getLanguage, getInitialOptions, getAvailableLanguages, getFallbackNamespaces, getTranslationNs, getTranslation, changeTranslation, events) { | ||
const plugins = { | ||
@@ -606,2 +667,5 @@ ui: undefined, | ||
} | ||
function storageLoadLanguage() { | ||
return handleRegularOrAsyncErr(events.onError, (e) => new LanguageStorageError('Tolgee: Failed to load language', e), () => { var _a; return (_a = instances.languageStorage) === null || _a === void 0 ? void 0 : _a.getLanguage(getCommonProps()); }); | ||
} | ||
function detectLanguage() { | ||
@@ -612,3 +676,6 @@ if (!instances.languageDetector) { | ||
const availableLanguages = getAvailableLanguages(); | ||
return instances.languageDetector.getLanguage(Object.assign({ availableLanguages }, getCommonProps())); | ||
return handleRegularOrAsyncErr(events.onError, (e) => new LanguageDetectorError('Tolgee: Failed to detect language', e), () => { | ||
var _a; | ||
return (_a = instances.languageDetector) === null || _a === void 0 ? void 0 : _a.getLanguage(Object.assign({ availableLanguages }, getCommonProps())); | ||
}); | ||
} | ||
@@ -650,3 +717,3 @@ function addBackend(backend) { | ||
findPositions, | ||
onPermanentChange, | ||
onPermanentChange: (data) => events.onPermanentChange.emit(data), | ||
}); | ||
@@ -669,5 +736,4 @@ (_b = instances.observer) === null || _b === void 0 ? void 0 : _b.run({ | ||
getInitialLanguage() { | ||
var _a; | ||
const availableLanguages = getAvailableLanguages(); | ||
const languageOrPromise = (_a = instances.languageStorage) === null || _a === void 0 ? void 0 : _a.getLanguage(getCommonProps()); | ||
const languageOrPromise = storageLoadLanguage(); | ||
return valueOrPromise(languageOrPromise, (language) => { | ||
@@ -682,4 +748,3 @@ if ((!availableLanguages || availableLanguages.includes(language)) && | ||
setStoredLanguage(language) { | ||
var _a; | ||
(_a = instances.languageStorage) === null || _a === void 0 ? void 0 : _a.setLanguage(language, getCommonProps()); | ||
return handleRegularOrAsyncErr(events.onError, (e) => new LanguageStorageError('Tolgee: Failed to store language', e), () => { var _a; return (_a = instances.languageStorage) === null || _a === void 0 ? void 0 : _a.setLanguage(language, getCommonProps()); }); | ||
}, | ||
@@ -693,9 +758,2 @@ getDevBackend() { | ||
namespace }, getCommonProps())); | ||
if (isPromise(data)) { | ||
return data === null || data === void 0 ? void 0 : data.catch((e) => { | ||
// eslint-disable-next-line no-console | ||
console.error(e); | ||
return {}; | ||
}); | ||
} | ||
if (data !== undefined) { | ||
@@ -989,4 +1047,4 @@ return data; | ||
const state = State(events.onLanguageChange, events.onPendingLanguageChange, events.onRunningChange); | ||
const pluginService = Plugins(state.getLanguage, state.getInitialOptions, state.getAvailableLanguages, getDefaultAndFallbackNs, getTranslationNs, getTranslation, changeTranslation, onPermanentChange); | ||
const cache = Cache(events.onCacheChange, pluginService.getBackendRecord, pluginService.getBackendDevRecord, state.withDefaultNs, state.isInitialLoading, fetchingObserver, loadingObserver); | ||
const pluginService = Plugins(state.getLanguage, state.getInitialOptions, state.getAvailableLanguages, getDefaultAndFallbackNs, getTranslationNs, getTranslation, changeTranslation, events); | ||
const cache = Cache(events, pluginService.getBackendRecord, pluginService.getBackendDevRecord, state.withDefaultNs, state.isInitialLoading, fetchingObserver, loadingObserver); | ||
if (options) { | ||
@@ -1030,8 +1088,2 @@ init(options); | ||
} | ||
function onPermanentChange(props) { | ||
events.onPermanentChange.emit({ | ||
key: props.key, | ||
namespace: props.namespace, | ||
}); | ||
} | ||
function init(options) { | ||
@@ -1127,3 +1179,3 @@ state.init(options); | ||
state.setLanguage(language); | ||
pluginService.setStoredLanguage(language); | ||
await pluginService.setStoredLanguage(language); | ||
} | ||
@@ -1561,2 +1613,5 @@ }, | ||
exports.FormatSimple = FormatSimple; | ||
exports.LanguageDetectorError = LanguageDetectorError; | ||
exports.LanguageStorageError = LanguageStorageError; | ||
exports.RecordFetchError = RecordFetchError; | ||
exports.TolgeeCore = TolgeeCore; | ||
@@ -1563,0 +1618,0 @@ exports.createFetchFunction = createFetchFunction; |
@@ -16,2 +16,21 @@ 'use strict'; | ||
} | ||
function handleRegularOrAsyncErr(onError, createError, callback) { | ||
function handle(e) { | ||
const error = createError(e); | ||
onError.emit(error); | ||
// eslint-disable-next-line no-console | ||
console.error(error); | ||
throw error; | ||
} | ||
try { | ||
const result = callback(); | ||
if (isPromise(result)) { | ||
return result.catch(handle); | ||
} | ||
return result; | ||
} | ||
catch (e) { | ||
handle(e); | ||
} | ||
} | ||
function missingOptionError(option) { | ||
@@ -191,2 +210,3 @@ const options = (Array.isArray(option) ? option : [option]).map((val) => `'${val}'`); | ||
onPermanentChange: EventEmitter(isActive), | ||
onError: EventEmitter(isActive), | ||
setEmitterActive(active) { | ||
@@ -215,2 +235,4 @@ emitterActive = active; | ||
return self.onPermanentChange.listen(handler); | ||
case 'error': | ||
return self.onError.listen(handler); | ||
} | ||
@@ -225,2 +247,28 @@ }), | ||
class RecordFetchError extends Error { | ||
constructor(descriptor, cause, isDev = false) { | ||
const { language, namespace } = descriptor; | ||
super(`Tolgee: Failed to fetch record for "${language}"${namespace && ` and "${namespace}"`}`); | ||
this.cause = cause; | ||
this.isDev = isDev; | ||
this.name = 'RecordFetchError'; | ||
this.language = language; | ||
this.namespace = namespace; | ||
} | ||
} | ||
class LanguageDetectorError extends Error { | ||
constructor(message, cause) { | ||
super(message); | ||
this.cause = cause; | ||
this.name = 'LanguageDetectorError'; | ||
} | ||
} | ||
class LanguageStorageError extends Error { | ||
constructor(message, cause) { | ||
super(message); | ||
this.cause = cause; | ||
this.name = 'LanguageStorageError'; | ||
} | ||
} | ||
const flattenTranslations = (data) => { | ||
@@ -258,3 +306,3 @@ const result = new Map(); | ||
function Cache(onCacheChange, backendGetRecord, backendGetDevRecord, withDefaultNs, isInitialLoading, fetchingObserver, loadingObserver) { | ||
function Cache(events, backendGetRecord, backendGetDevRecord, withDefaultNs, isInitialLoading, fetchingObserver, loadingObserver) { | ||
const asyncRequests = new Map(); | ||
@@ -270,3 +318,3 @@ const cache = new Map(); | ||
}); | ||
onCacheChange.emit(descriptor); | ||
events.onCacheChange.emit(descriptor); | ||
} | ||
@@ -277,21 +325,34 @@ /** | ||
function fetchProd(keyObject) { | ||
let dataPromise = undefined; | ||
if (!dataPromise) { | ||
let dataOrPromise = undefined; | ||
if (!dataOrPromise) { | ||
const staticDataValue = staticData[encodeCacheKey(keyObject)]; | ||
if (typeof staticDataValue === 'function') { | ||
dataPromise = staticDataValue(); | ||
dataOrPromise = staticDataValue(); | ||
} | ||
} | ||
if (!dataPromise) { | ||
dataPromise = backendGetRecord(keyObject); | ||
if (!dataOrPromise) { | ||
dataOrPromise = backendGetRecord(keyObject); | ||
} | ||
return dataPromise; | ||
if (isPromise(dataOrPromise)) { | ||
return dataOrPromise === null || dataOrPromise === void 0 ? void 0 : dataOrPromise.catch((e) => { | ||
const error = new RecordFetchError(keyObject, e); | ||
events.onError.emit(error); | ||
// eslint-disable-next-line no-console | ||
console.error(error); | ||
throw error; | ||
}); | ||
} | ||
else { | ||
return dataOrPromise; | ||
} | ||
} | ||
function fetchData(keyObject, isDev) { | ||
var _a; | ||
let dataPromise = undefined; | ||
let dataOrPromise = undefined; | ||
if (isDev) { | ||
dataPromise = (_a = backendGetDevRecord(keyObject)) === null || _a === void 0 ? void 0 : _a.catch(() => { | ||
dataOrPromise = (_a = backendGetDevRecord(keyObject)) === null || _a === void 0 ? void 0 : _a.catch((e) => { | ||
const error = new RecordFetchError(keyObject, e, true); | ||
events.onError.emit(error); | ||
// eslint-disable-next-line no-console | ||
console.warn(`Tolgee: Failed to fetch data from dev backend`); | ||
console.warn(error); | ||
// fallback to prod fetch if dev fails | ||
@@ -301,6 +362,6 @@ return fetchProd(keyObject); | ||
} | ||
if (!dataPromise) { | ||
dataPromise = fetchProd(keyObject); | ||
if (!dataOrPromise) { | ||
dataOrPromise = fetchProd(keyObject); | ||
} | ||
return dataPromise; | ||
return dataOrPromise; | ||
} | ||
@@ -374,3 +435,3 @@ const self = Object.freeze({ | ||
record === null || record === void 0 ? void 0 : record.set(key, value); | ||
onCacheChange.emit(Object.assign(Object.assign({}, descriptor), { key })); | ||
events.onCacheChange.emit(Object.assign(Object.assign({}, descriptor), { key })); | ||
}, | ||
@@ -535,3 +596,3 @@ isFetching(ns) { | ||
function Plugins(getLanguage, getInitialOptions, getAvailableLanguages, getFallbackNamespaces, getTranslationNs, getTranslation, changeTranslation, onPermanentChange) { | ||
function Plugins(getLanguage, getInitialOptions, getAvailableLanguages, getFallbackNamespaces, getTranslationNs, getTranslation, changeTranslation, events) { | ||
const plugins = { | ||
@@ -606,2 +667,5 @@ ui: undefined, | ||
} | ||
function storageLoadLanguage() { | ||
return handleRegularOrAsyncErr(events.onError, (e) => new LanguageStorageError('Tolgee: Failed to load language', e), () => { var _a; return (_a = instances.languageStorage) === null || _a === void 0 ? void 0 : _a.getLanguage(getCommonProps()); }); | ||
} | ||
function detectLanguage() { | ||
@@ -612,3 +676,6 @@ if (!instances.languageDetector) { | ||
const availableLanguages = getAvailableLanguages(); | ||
return instances.languageDetector.getLanguage(Object.assign({ availableLanguages }, getCommonProps())); | ||
return handleRegularOrAsyncErr(events.onError, (e) => new LanguageDetectorError('Tolgee: Failed to detect language', e), () => { | ||
var _a; | ||
return (_a = instances.languageDetector) === null || _a === void 0 ? void 0 : _a.getLanguage(Object.assign({ availableLanguages }, getCommonProps())); | ||
}); | ||
} | ||
@@ -650,3 +717,3 @@ function addBackend(backend) { | ||
findPositions, | ||
onPermanentChange, | ||
onPermanentChange: (data) => events.onPermanentChange.emit(data), | ||
}); | ||
@@ -669,5 +736,4 @@ (_b = instances.observer) === null || _b === void 0 ? void 0 : _b.run({ | ||
getInitialLanguage() { | ||
var _a; | ||
const availableLanguages = getAvailableLanguages(); | ||
const languageOrPromise = (_a = instances.languageStorage) === null || _a === void 0 ? void 0 : _a.getLanguage(getCommonProps()); | ||
const languageOrPromise = storageLoadLanguage(); | ||
return valueOrPromise(languageOrPromise, (language) => { | ||
@@ -682,4 +748,3 @@ if ((!availableLanguages || availableLanguages.includes(language)) && | ||
setStoredLanguage(language) { | ||
var _a; | ||
(_a = instances.languageStorage) === null || _a === void 0 ? void 0 : _a.setLanguage(language, getCommonProps()); | ||
return handleRegularOrAsyncErr(events.onError, (e) => new LanguageStorageError('Tolgee: Failed to store language', e), () => { var _a; return (_a = instances.languageStorage) === null || _a === void 0 ? void 0 : _a.setLanguage(language, getCommonProps()); }); | ||
}, | ||
@@ -693,9 +758,2 @@ getDevBackend() { | ||
namespace }, getCommonProps())); | ||
if (isPromise(data)) { | ||
return data === null || data === void 0 ? void 0 : data.catch((e) => { | ||
// eslint-disable-next-line no-console | ||
console.error(e); | ||
return {}; | ||
}); | ||
} | ||
if (data !== undefined) { | ||
@@ -989,4 +1047,4 @@ return data; | ||
const state = State(events.onLanguageChange, events.onPendingLanguageChange, events.onRunningChange); | ||
const pluginService = Plugins(state.getLanguage, state.getInitialOptions, state.getAvailableLanguages, getDefaultAndFallbackNs, getTranslationNs, getTranslation, changeTranslation, onPermanentChange); | ||
const cache = Cache(events.onCacheChange, pluginService.getBackendRecord, pluginService.getBackendDevRecord, state.withDefaultNs, state.isInitialLoading, fetchingObserver, loadingObserver); | ||
const pluginService = Plugins(state.getLanguage, state.getInitialOptions, state.getAvailableLanguages, getDefaultAndFallbackNs, getTranslationNs, getTranslation, changeTranslation, events); | ||
const cache = Cache(events, pluginService.getBackendRecord, pluginService.getBackendDevRecord, state.withDefaultNs, state.isInitialLoading, fetchingObserver, loadingObserver); | ||
if (options) { | ||
@@ -1030,8 +1088,2 @@ init(options); | ||
} | ||
function onPermanentChange(props) { | ||
events.onPermanentChange.emit({ | ||
key: props.key, | ||
namespace: props.namespace, | ||
}); | ||
} | ||
function init(options) { | ||
@@ -1127,3 +1179,3 @@ state.init(options); | ||
state.setLanguage(language); | ||
pluginService.setStoredLanguage(language); | ||
await pluginService.setStoredLanguage(language); | ||
} | ||
@@ -1561,2 +1613,5 @@ }, | ||
exports.FormatSimple = FormatSimple; | ||
exports.LanguageDetectorError = LanguageDetectorError; | ||
exports.LanguageStorageError = LanguageStorageError; | ||
exports.RecordFetchError = RecordFetchError; | ||
exports.TolgeeCore = TolgeeCore; | ||
@@ -1563,0 +1618,0 @@ exports.createFetchFunction = createFetchFunction; |
@@ -1,2 +0,2 @@ | ||
"use strict";function e(e){return Boolean(e&&"function"==typeof e.then)}function n(n,t){return e(n)?Promise.resolve(n).then(t):t(n)}function t(e){const n=(Array.isArray(e)?e:[e]).map((e=>`'${e}'`)),t=n.slice(-2).join(" or ");return`Tolgee: You need to specify ${[...n.slice(0,-2),t].join(", ")} option`}function a(e){return"string"==typeof e?[e]:Array.isArray(e)?e:void 0}function i(e){return a(e)||[]}function o(e,n){return"object"!=typeof(t=n)||Array.isArray(t)||null===t?i(n):i(null==n?void 0:n[e]);var t}function s(e){return Array.from(new Set(e))}function r(e){return e?e.replace(/\/+$/,""):e}Object.defineProperty(exports,"__esModule",{value:!0});const g=(e,n)=>fetch(e,n),c=(e=g)=>(n,t)=>e(n,Object.assign(Object.assign({},t),{headers:Object.assign({"X-Tolgee-SDK-Type":"JS","X-Tolgee-SDK-Version":process.env.TOLGEE_UI_VERSION||"prerelease"},null==t?void 0:t.headers)}));function l(e){let n=[];return Object.freeze({listen(e){const t=n=>{e(n)};return n.push(t),{unsubscribe(){n=n.filter((e=>t!==e))}}},emit(t){e()&&n.forEach((e=>e({value:t})))}})}function u(e,n,t){const a=new Set,o=new Set;let s=[];function r(){if(0===s.length)return;const e=s;s=[],a.forEach((e=>{e({value:void 0})}));let t=new Set;e.forEach((e=>{void 0===e?t=void 0:void 0!==t&&e.forEach((e=>t.add(e)))}));!function(e){const t=new Set(n());o.forEach((n=>{(void 0===e||-1!==(null==e?void 0:e.findIndex((e=>t.has(e)||n.namespaces.has(e)))))&&n.fn({value:void 0})}))}(t?Array.from(t.keys()):void 0)}return Object.freeze({emit(n,t){e()&&(s.push(n),t?setTimeout(r,0):r())},listen(e){a.add(e);return{unsubscribe:()=>{a.delete(e)}}},listenSome(e){const n={fn:n=>{e(n)},namespaces:new Set};o.add(n);const a={unsubscribe:()=>{o.delete(n)},subscribeNs:e=>(i(e).forEach((e=>n.namespaces.add(e))),void 0===e&&n.namespaces.add(t()),a)};return a}})}const d=e=>{const n=new Map;return Object.entries(e).forEach((([e,t])=>{null!=t&&("object"!=typeof t?n.set(e,t):d(t).forEach(((t,a)=>{n.set(e+"."+a,t)})))})),n},p=e=>{const[n,...t]=e.split(":");return{language:n,namespace:t.join(":")||""}},f=({language:e,namespace:n})=>n?`${e}:${n}`:e;function v(e,n,t,a,o,r,g){const c=new Map,l=new Map;let u={},v=0;function h(n,t,a){const i=f(n);l.set(i,{data:d(t),version:a}),e.emit(n)}function m(e){let t;if(!t){const n=u[f(e)];"function"==typeof n&&(t=n())}return t||(t=n(e)),t}const b=Object.freeze({addStaticData(e){e&&(u=Object.assign(Object.assign({},u),e),Object.entries(e).forEach((([e,n])=>{if("function"!=typeof n){const t=p(e),a=l.get(e);a&&0!==a.version||h(t,n,0)}})))},invalidate(){c.clear(),v+=1},addRecord(e,n){h(e,n,v)},exists(e,n=!1){const t=l.get(f(e));return t&&n?t.version===v:Boolean(t)},getRecord(e){var n;return null===(n=l.get(f(a(e))))||void 0===n?void 0:n.data},getTranslation(e,n){var t;return null===(t=l.get(f(e)))||void 0===t?void 0:t.data.get(n)},getTranslationNs(e,n,t){var a;for(const i of e)for(const e of n){const n=null===(a=l.get(f({language:e,namespace:i})))||void 0===a?void 0:a.data.get(t);if(null!=n)return[i]}return s(e)},getTranslationFallback(e,n,t){var a;for(const i of e)for(const e of n){const n=null===(a=l.get(f({language:e,namespace:i})))||void 0===a?void 0:a.data.get(t);if(null!=n)return n}},changeTranslation(n,t,a){var i;const o=null===(i=l.get(f(n)))||void 0===i?void 0:i.data;null==o||o.set(t,a),e.emit(Object.assign(Object.assign({},n),{key:t}))},isFetching(e){if(o())return!0;if(void 0===e)return c.size>0;const n=i(e);return Boolean(Array.from(c.keys()).find((e=>n.includes(p(e).namespace))))},isLoading(e,n){const t=i(n);return Boolean(o()||Array.from(c.keys()).find((n=>{const a=p(n);return(!t.length||t.includes(a.namespace))&&!b.exists({namespace:a.namespace,language:e})})))},async loadRecords(e,n){const i=e.map((e=>{const i=a(e),o=f(i),s=c.get(o);if(s)return{new:!1,promise:s,keyObject:i,cacheKey:o};const r=function(e,n){var a;let i;return n&&(i=null===(a=t(e))||void 0===a?void 0:a.catch((()=>(console.warn("Tolgee: Failed to fetch data from dev backend"),m(e))))),i||(i=m(e)),i}(i,n)||Promise.resolve(void 0);return c.set(o,r),{new:!0,promise:r,keyObject:i,cacheKey:o}}));r.notify(),g.notify();const o=await Promise.all(i.map((e=>e.promise)));return i.forEach(((e,n)=>{const t=c.get(e.cacheKey)!==e.promise;if(e.new&&!t){c.delete(e.cacheKey);const t=o[n];t?b.addRecord(e.keyObject,t):b.getRecord(e.keyObject)||b.addRecord(e.keyObject,{})}})),r.notify(),g.notify(),i.map((e=>b.getRecord(e.keyObject)))},getAllRecords:()=>Array.from(l.entries()).map((([e,n])=>Object.assign(Object.assign({},p(e)),{data:n.data})))});return b}function h(e,n){var t={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&n.indexOf(a)<0&&(t[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(a=Object.getOwnPropertySymbols(e);i<a.length;i++)n.indexOf(a[i])<0&&Object.prototype.propertyIsEnumerable.call(e,a[i])&&(t[a[i]]=e[a[i]])}return t}const m="invalid",b={defaultNs:"",observerOptions:{tagAttributes:{textarea:["placeholder"],input:["value","placeholder"],img:["alt"],"*":["aria-label","title"]},restrictedElements:["script","style"],highlightKeys:["Alt"],highlightColor:"rgb(255, 0, 0)",highlightWidth:5,inputPrefix:"%-%tolgee:",inputSuffix:"%-%",passToParent:["option","optgroup"],fullKeyEncode:!1},observerType:"invisible",onFormatError:m,apiUrl:"https://app.tolgee.io",fetch:c(),onTranslationMissing:({key:e})=>e},O=(...e)=>{let n={};return e.forEach((e=>{n=Object.assign(Object.assign(Object.assign({},n),e),{observerOptions:Object.assign(Object.assign({},n.observerOptions),null==e?void 0:e.observerOptions)})})),n};function y(e,n){const t=O(b,null==n?void 0:n.initialOptions,e);return t.apiUrl=r(t.apiUrl),(null==e?void 0:e.fetch)&&(t.fetch=c(e.fetch)),{initialOptions:t,activeNamespaces:(null==n?void 0:n.activeNamespaces)||new Map,language:null==n?void 0:n.language,pendingLanguage:null==n?void 0:n.language,isInitialLoading:!1,isRunning:!1}}function L(t,a,i,o,s,r,g,c){const l={ui:void 0},u={formatters:[],finalFormatter:void 0,observer:void 0,devBackend:void 0,backends:[],ui:void 0,languageDetector:void 0,languageStorage:void 0},d=async({keysAndDefaults:e,event:n})=>{var t;const a=e.map((({key:e,ns:n,defaultValue:t})=>({key:e,defaultValue:t,fallbackNamespaces:o(n),namespace:s({key:e,ns:n})[0],translation:r({key:e,ns:n})})));null===(t=u.ui)||void 0===t||t.handleElementClick(a,n)},p=(e,n)=>{var t;return(null===(t=u.observer)||void 0===t?void 0:t.findPositions(e,n))||[]};function f(e){const n=r({key:e.key,ns:e.ns});return D.formatTranslation(Object.assign(Object.assign({},e),{translation:n,formatEnabled:!0}))}function v(){return{fetch:a().fetch}}function b(e){u.observer=null==e?void 0:e()}function O(){return Boolean(u.observer)}function y(e){e&&u.formatters.push(e)}function L(e){u.finalFormatter=e}function j(e){l.ui=e}function k(){return Boolean(l.ui)}function R(e){u.languageStorage=e}function w(e){u.languageDetector=e}function E(e){e&&u.backends.push(e)}function N(e){u.devBackend=e}const D=Object.freeze({addPlugin:function(e,n){n(e,Object.freeze({setFinalFormatter:L,addFormatter:y,setObserver:b,hasObserver:O,setUi:j,hasUi:k,setDevBackend:N,addBackend:E,setLanguageDetector:w,setLanguageStorage:R}))},run(){var e,n;const{apiKey:t,apiUrl:i,projectId:o,observerOptions:s}=a();u.ui=null===(e=l.ui)||void 0===e?void 0:e.call(l,{apiKey:t,apiUrl:i,projectId:o,highlight:D.highlight,changeTranslation:g,findPositions:p,onPermanentChange:c}),null===(n=u.observer)||void 0===n||n.run({mouseHighlight:!0,options:s,translate:f,onClick:d})},stop(){var e;u.ui=void 0,null===(e=u.observer)||void 0===e||e.stop()},getLanguageStorage:()=>u.languageStorage,getInitialLanguage(){var e;const t=i();return n(null===(e=u.languageStorage)||void 0===e?void 0:e.getLanguage(v()),(e=>t&&!t.includes(e)||!e?function(){if(!u.languageDetector)return;const e=i();return u.languageDetector.getLanguage(Object.assign({availableLanguages:e},v()))}():e))},setStoredLanguage(e){var n;null===(n=u.languageStorage)||void 0===n||n.setLanguage(e,v())},getDevBackend:()=>u.devBackend,getBackendRecord:({language:n,namespace:t})=>{for(const a of u.backends){const i=a.getRecord(Object.assign({language:n,namespace:t},v()));if(e(i))return null==i?void 0:i.catch((e=>(console.error(e),{})));if(void 0!==i)return i}},getBackendDevRecord:({language:e,namespace:n})=>{var t;const{apiKey:i,apiUrl:o,projectId:s}=a();return null===(t=u.devBackend)||void 0===t?void 0:t.getRecord(Object.assign({apiKey:i,apiUrl:o,projectId:s,language:e,namespace:n},v()))},getLanguageDetector:()=>u.languageDetector,retranslate(){var e;null===(e=u.observer)||void 0===e||e.retranslate()},highlight:(e,n)=>{var t,a;return(null===(a=null===(t=u.observer)||void 0===t?void 0:t.highlight)||void 0===a?void 0:a.call(t,e,n))||{unhighlight(){}}},unwrap(e){var n;return u.observer?null===(n=u.observer)||void 0===n?void 0:n.unwrap(e):{text:e,keys:[]}},wrap(e){var n;return u.observer?null===(n=u.observer)||void 0===n?void 0:n.wrap(e):e.translation},hasDevBackend:()=>Boolean(D.getDevBackend()),formatTranslation(e){var n,{formatEnabled:i}=e,o=h(e,["formatEnabled"]);const{key:s,translation:r,defaultValue:g,noWrap:c,params:l,ns:d,orEmpty:p}=o,f=null!=r?r:g;let v="";null==r&&(v=a().onTranslationMissing(o));let b=null!=f?f:p?"":v;const O=t(),y=i||!(null===(n=u.observer)||void 0===n?void 0:n.outputNotFormattable),L=e=>u.observer&&!c?u.observer.wrap({key:s,translation:e,defaultValue:g,params:l,ns:d}):e;b=L(b);try{if(f&&O&&y)for(const e of u.formatters)b=e.format({translation:b,language:O,params:l});u.finalFormatter&&f&&O&&y&&(b=u.finalFormatter.format({translation:b,language:O,params:l}))}catch(e){console.error(e);const n=("string"==typeof(j=e)?j:"string"==typeof(null==j?void 0:j.message)?j.message:void 0)||m,t=a().onFormatError,i=typeof t;b="string"===i?t:"function"===i?t(n,o):m,b=L(b)}var j;return b}});return D}const j=(e,n,t)=>{let a=e;return Object.freeze({init(e){a=e},notify(){const e=n();a!==e&&t(e),a=e}})};const k=(e,...n)=>{let t,a={};return"object"==typeof e?a=e:(a.key=e,"string"==typeof n[0]?(a.defaultValue=n[0],t=n[1]):"object"==typeof n[0]&&(t=n[0])),t&&(a=Object.assign(Object.assign({},function(e){var{ns:n,noWrap:t,orEmpty:a,params:i,language:o}=e,s=h(e,["ns","noWrap","orEmpty","params","language"]);const r={ns:n,noWrap:t,orEmpty:a,language:o};return Object.assign(Object.assign({},r),{params:Object.assign({},s)})}(t)),a)),a};function R({options:a}){const g=function(e,n){let t=!0;function a(){return t}const i=Object.freeze({onPendingLanguageChange:l(a),onLanguageChange:l(a),onLoadingChange:l(a),onFetchingChange:l(a),onInitialLoaded:l(a),onRunningChange:l(a),onCacheChange:l(a),onUpdate:u(a,e,n),onPermanentChange:l(a),setEmitterActive(e){t=e},on:(e,n)=>{switch(e){case"pendingLanguage":return i.onPendingLanguageChange.listen(n);case"language":return i.onLanguageChange.listen(n);case"loading":return i.onLoadingChange.listen(n);case"fetching":return i.onFetchingChange.listen(n);case"initialLoad":return i.onInitialLoaded.listen(n);case"running":return i.onRunningChange.listen(n);case"cache":return i.onCacheChange.listen(n);case"update":return i.onUpdate.listen(n);case"permanentChange":return i.onPermanentChange.listen(n)}}});return i.onInitialLoaded.listen((()=>i.onUpdate.emit())),i.onLanguageChange.listen((()=>i.onUpdate.emit())),i.onCacheChange.listen((({value:e})=>i.onUpdate.emit([e.namespace],!0))),i}(O,R),c=j(!1,(()=>m.isFetching()),g.onFetchingChange.emit),d=j(!1,(()=>S.isLoading()),g.onLoadingChange.emit),f=function(e,n,t){let a,g=y();const c=Object.freeze({init(e){g=y(e,g)},isRunning:()=>g.isRunning,setRunning(e){g.isRunning!==e&&(g.isRunning=e,t.emit(e))},isInitialLoading:()=>g.isInitialLoading,setInitialLoading(e){g.isInitialLoading=e},getLanguage:()=>g.language||g.initialOptions.language,setLanguage(n){g.language!==n&&(g.language=n,e.emit(n))},getPendingLanguage:()=>g.pendingLanguage||c.getLanguage(),setPendingLanguage(e){g.pendingLanguage!==e&&(g.pendingLanguage=e,n.emit(e))},getInitialOptions:()=>Object.assign(Object.assign({},g.initialOptions),a),addActiveNs(e){i(e).forEach((e=>{const n=g.activeNamespaces.get(e);void 0!==n?g.activeNamespaces.set(e,n+1):g.activeNamespaces.set(e,1)}))},removeActiveNs(e){i(e).forEach((e=>{const n=g.activeNamespaces.get(e);void 0!==n&&n>1?g.activeNamespaces.set(e,n-1):g.activeNamespaces.delete(e)}))},getRequiredNamespaces:()=>s([...g.initialOptions.ns||[g.initialOptions.defaultNs],...i(g.initialOptions.fallbackNs),...g.activeNamespaces.keys()]),getFallbackLangs(e){const n=e||c.getLanguage();return n?s([n,...o(n,g.initialOptions.fallbackLanguage)]):[]},getFallbackNs:()=>i(g.initialOptions.fallbackNs),getDefaultNs:e=>void 0===e?g.initialOptions.defaultNs:e,getAvailableLanguages(){if(g.initialOptions.availableLanguages)return g.initialOptions.availableLanguages;if(g.initialOptions.staticData){const e=Object.keys(g.initialOptions.staticData).map((e=>p(e).language));return Array.from(new Set(e))}},withDefaultNs:e=>({namespace:void 0===e.namespace?c.getInitialOptions().defaultNs:e.namespace,language:e.language}),overrideCredentials(e){a=e?Object.assign(Object.assign({},e),{apiUrl:r(e.apiUrl)}):void 0}});return c}(g.onLanguageChange,g.onPendingLanguageChange,g.onRunningChange),h=L(f.getLanguage,f.getInitialOptions,f.getAvailableLanguages,w,A,F,N,(function(e){g.onPermanentChange.emit({key:e.key,namespace:e.namespace})})),m=v(g.onCacheChange,h.getBackendRecord,h.getBackendDevRecord,f.withDefaultNs,f.isInitialLoading,c,d);let b;function O(){return f.getFallbackNs()}function R(e){return f.getDefaultNs(e)}function w(e){return[...i(R(e)),...O()]}function E(e){return[...i(null!=e?e:R()),...f.getRequiredNamespaces()]}function N(e,n,t){const a=f.withDefaultNs(e),i=m.getTranslation(a,n);return m.changeTranslation(a,n,t),{revert(){m.changeTranslation(a,n,i)}}}function D(e){f.init(e),m.addStaticData(f.getInitialOptions().staticData)}function C(e,t){const a=function(e,n){const t=f.getFallbackLangs(e),a=E(n),i=[];return t.forEach((e=>{a.forEach((n=>{m.exists({language:e,namespace:n},!0)||i.push({language:e,namespace:n})}))})),i}(e,t);if(a.length)return n(S.loadRecords(a),(()=>{}))}function A({key:e,ns:n}){const t=f.getFallbackLangs(),a=w(null!=n?n:void 0);return m.getTranslationNs(a,t,e)}function F({key:e,ns:n,language:t}){const a=w(null!=n?n:void 0),i=f.getFallbackLangs(t);return m.getTranslationFallback(a,i,e)}function I(){const t=n(function(){if(f.getLanguage())return;return n(h.getInitialLanguage(),(e=>{const n=e||f.getInitialOptions().defaultLanguage;n&&f.setLanguage(n)}))}(),(()=>C()));if(e(t))return f.setInitialLoading(!0),c.notify(),d.notify(),Promise.resolve(t).then((()=>{f.setInitialLoading(!1),c.notify(),d.notify(),g.onInitialLoaded.emit()}));g.onInitialLoaded.emit()}a&&D(a),g.onUpdate.listen((()=>{f.isRunning()&&h.retranslate()}));const S=Object.freeze(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},g),f),h),m),{init:D,getTranslation:F,changeTranslation:N,getTranslationNs:A,getDefaultAndFallbackNs:w,async changeLanguage(e){f.getPendingLanguage()===e&&f.getLanguage()===e||(f.setPendingLanguage(e),f.isRunning()&&await C(e),e===f.getPendingLanguage()&&(f.setLanguage(e),h.setStoredLanguage(e)))},async addActiveNs(e,n){n||f.addActiveNs(e),f.isRunning()&&await C(void 0,e)},loadRecords:e=>m.loadRecords(e,S.isDev()),loadRecord:async e=>(await S.loadRecords([e]))[0],isLoading:e=>m.isLoading(f.getLanguage(),e),isLoaded(e){const n=f.getLanguage();if(!n)return!1;const t=f.getFallbackLangs(n),a=E(e),i=[];return t.forEach((e=>{a.forEach((n=>{m.exists({language:e,namespace:n})||i.push({language:e,namespace:n})}))})),0===i.length},t:(...e)=>{const n=k(...e),t=F(n);return h.formatTranslation(Object.assign(Object.assign({},n),{translation:t}))},isDev:()=>Boolean(f.getInitialOptions().apiKey&&f.getInitialOptions().apiUrl),run:()=>(function(){if((h.getLanguageDetector()||h.getLanguageStorage())&&!f.getAvailableLanguages())throw new Error(t("availableLanguages"));if(!f.getLanguage()&&!f.getInitialOptions().defaultLanguage)throw new Error(t(["defaultLanguage","language"]))}(),f.isRunning()||(f.setRunning(!0),h.run(),b=I()),Promise.resolve(b)),stop(){f.isRunning()&&(h.stop(),f.setRunning(!1))}}));return S}const w=0,E=1,N=2;class D extends Error{constructor(e,n,t){let a;a=e===w?"Empty parameter":e===E?"Unexpected character":"Unexpected end",super(`Tolgee parser: ${a} at ${n} in "${t}"`),this.code=e,this.index=n}}function C(e){return/\s/.test(e)}const A=0,F=1,I=2,S=3,P=4,T=new Set([I,F,A]),U="'",x=new Set(["{","}",U]),B=e=>/[0-9a-zA-Z_]/.test(e);function z(e,n){const[t,a]=function(e){let n=A,t="",a="",i="";const o=[],s=[];let r=0;function g(n){throw new D(n,r,e)}const c=()=>{o.push(t),t=""},l=()=>{""===a&&g(w),s.push(a),a=""};for(r=0;r<e.length;r++)switch(i=e[r],n){case A:i===U?(t+=i,n=F):"{"===i?(c(),n=S):(t+=i,n=A);break;case F:x.has(i)?(t=t.slice(0,-1)+i,n=I):(t+=i,n=A);break;case I:i===U?n=A:(t+=i,n=I);break;case S:"}"===i?(l(),n=A):C(i)?""!==a&&(l(),n=P):(B(i)||g(E),a+=i,n=S);break;case P:"}"==i?n=A:C(i)?n=P:g(E)}return T.has(n)||g(N),c(),[o,s]}(e),i=[t[0]];for(let o=1;o<t.length;o++){const s=null==n?void 0:n[a[o-1]];if(void 0===s)throw new Error(`Missing parameter "${a[o-1]}" in "${e}"`);i.push(String(s)),i.push(t[o])}return i.join("")}exports.FormatSimple=()=>(e,n)=>(n.setFinalFormatter({format:({translation:e,params:n})=>z(e,n)}),e),exports.TolgeeCore=()=>{const e={plugins:[],options:{}},n=Object.freeze({use:t=>(e.plugins.push(t),n),updateDefaults:t=>(e.options=O(e.options,t),n),init(n){const t=function(e){const n=R({options:e});function t(e){const t=n.isRunning();t&&n.stop(),e(),n.isDev()&&n.invalidate(),t&&n.run()}n.isDev()&&n.invalidate();const a=Object.freeze({on:n.on,onNsUpdate:n.onUpdate.listenSome,setEmitterActive:n.setEmitterActive,getLanguage:n.getLanguage,getPendingLanguage:n.getPendingLanguage,changeLanguage:n.changeLanguage,changeTranslation:n.changeTranslation,addActiveNs:n.addActiveNs,removeActiveNs:n.removeActiveNs,loadRecords:n.loadRecords,loadRecord:n.loadRecord,addStaticData:n.addStaticData,getRecord:n.getRecord,getAllRecords:n.getAllRecords,isLoaded:n.isLoaded,isInitialLoading:n.isInitialLoading,isLoading:n.isLoading,isFetching:n.isFetching,isRunning:n.isRunning,run:n.run,stop:n.stop,t:n.t,highlight:n.highlight,getInitialOptions:n.getInitialOptions,isDev:n.isDev,wrap:n.wrap,unwrap:n.unwrap,overrideCredentials(e){t((()=>n.overrideCredentials(e)))},addPlugin(e){e&&t((()=>n.addPlugin(a,e)))},updateOptions(e){e&&t((()=>n.init(e)))}});return a}(O(e.options,n));return e.plugins.forEach(t.addPlugin),t}});return n},exports.createFetchFunction=c,exports.getFallback=a,exports.getFallbackArray=i,exports.getTranslateProps=k; | ||
"use strict";function e(e){return Boolean(e&&"function"==typeof e.then)}function n(n,t){return e(n)?Promise.resolve(n).then(t):t(n)}function t(n,t,a){function i(e){const a=t(e);throw n.emit(a),console.error(a),a}try{const n=a();return e(n)?n.catch(i):n}catch(e){i(e)}}function a(e){const n=(Array.isArray(e)?e:[e]).map((e=>`'${e}'`)),t=n.slice(-2).join(" or ");return`Tolgee: You need to specify ${[...n.slice(0,-2),t].join(", ")} option`}function i(e){return"string"==typeof e?[e]:Array.isArray(e)?e:void 0}function o(e){return i(e)||[]}function r(e,n){return"object"!=typeof(t=n)||Array.isArray(t)||null===t?o(n):o(null==n?void 0:n[e]);var t}function s(e){return Array.from(new Set(e))}function g(e){return e?e.replace(/\/+$/,""):e}Object.defineProperty(exports,"__esModule",{value:!0});const c=(e,n)=>fetch(e,n),l=(e=c)=>(n,t)=>e(n,Object.assign(Object.assign({},t),{headers:Object.assign({"X-Tolgee-SDK-Type":"JS","X-Tolgee-SDK-Version":process.env.TOLGEE_UI_VERSION||"prerelease"},null==t?void 0:t.headers)}));function u(e){let n=[];return Object.freeze({listen(e){const t=n=>{e(n)};return n.push(t),{unsubscribe(){n=n.filter((e=>t!==e))}}},emit(t){e()&&n.forEach((e=>e({value:t})))}})}function d(e,n,t){const a=new Set,i=new Set;let r=[];function s(){if(0===r.length)return;const e=r;r=[],a.forEach((e=>{e({value:void 0})}));let t=new Set;e.forEach((e=>{void 0===e?t=void 0:void 0!==t&&e.forEach((e=>t.add(e)))}));!function(e){const t=new Set(n());i.forEach((n=>{(void 0===e||-1!==(null==e?void 0:e.findIndex((e=>t.has(e)||n.namespaces.has(e)))))&&n.fn({value:void 0})}))}(t?Array.from(t.keys()):void 0)}return Object.freeze({emit(n,t){e()&&(r.push(n),t?setTimeout(s,0):s())},listen(e){a.add(e);return{unsubscribe:()=>{a.delete(e)}}},listenSome(e){const n={fn:n=>{e(n)},namespaces:new Set};i.add(n);const a={unsubscribe:()=>{i.delete(n)},subscribeNs:e=>(o(e).forEach((e=>n.namespaces.add(e))),void 0===e&&n.namespaces.add(t()),a)};return a}})}class p extends Error{constructor(e,n,t=!1){const{language:a,namespace:i}=e;super(`Tolgee: Failed to fetch record for "${a}"${i&&` and "${i}"`}`),this.cause=n,this.isDev=t,this.name="RecordFetchError",this.language=a,this.namespace=i}}class f extends Error{constructor(e,n){super(e),this.cause=n,this.name="LanguageDetectorError"}}class v extends Error{constructor(e,n){super(e),this.cause=n,this.name="LanguageStorageError"}}const h=e=>{const n=new Map;return Object.entries(e).forEach((([e,t])=>{null!=t&&("object"!=typeof t?n.set(e,t):h(t).forEach(((t,a)=>{n.set(e+"."+a,t)})))})),n},m=e=>{const[n,...t]=e.split(":");return{language:n,namespace:t.join(":")||""}},b=({language:e,namespace:n})=>n?`${e}:${n}`:e;function O(n,t,a,i,r,g,c){const l=new Map,u=new Map;let d={},f=0;function v(e,t,a){const i=b(e);u.set(i,{data:h(t),version:a}),n.onCacheChange.emit(e)}function O(a){let i;if(!i){const e=d[b(a)];"function"==typeof e&&(i=e())}return i||(i=t(a)),e(i)?null==i?void 0:i.catch((e=>{const t=new p(a,e);throw n.onError.emit(t),console.error(t),t})):i}const L=Object.freeze({addStaticData(e){e&&(d=Object.assign(Object.assign({},d),e),Object.entries(e).forEach((([e,n])=>{if("function"!=typeof n){const t=m(e),a=u.get(e);a&&0!==a.version||v(t,n,0)}})))},invalidate(){l.clear(),f+=1},addRecord(e,n){v(e,n,f)},exists(e,n=!1){const t=u.get(b(e));return t&&n?t.version===f:Boolean(t)},getRecord(e){var n;return null===(n=u.get(b(i(e))))||void 0===n?void 0:n.data},getTranslation(e,n){var t;return null===(t=u.get(b(e)))||void 0===t?void 0:t.data.get(n)},getTranslationNs(e,n,t){var a;for(const i of e)for(const e of n){const n=null===(a=u.get(b({language:e,namespace:i})))||void 0===a?void 0:a.data.get(t);if(null!=n)return[i]}return s(e)},getTranslationFallback(e,n,t){var a;for(const i of e)for(const e of n){const n=null===(a=u.get(b({language:e,namespace:i})))||void 0===a?void 0:a.data.get(t);if(null!=n)return n}},changeTranslation(e,t,a){var i;const o=null===(i=u.get(b(e)))||void 0===i?void 0:i.data;null==o||o.set(t,a),n.onCacheChange.emit(Object.assign(Object.assign({},e),{key:t}))},isFetching(e){if(r())return!0;if(void 0===e)return l.size>0;const n=o(e);return Boolean(Array.from(l.keys()).find((e=>n.includes(m(e).namespace))))},isLoading(e,n){const t=o(n);return Boolean(r()||Array.from(l.keys()).find((n=>{const a=m(n);return(!t.length||t.includes(a.namespace))&&!L.exists({namespace:a.namespace,language:e})})))},async loadRecords(e,t){const o=e.map((e=>{const o=i(e),r=b(o),s=l.get(r);if(s)return{new:!1,promise:s,keyObject:o,cacheKey:r};const g=function(e,t){var i;let o;return t&&(o=null===(i=a(e))||void 0===i?void 0:i.catch((t=>{const a=new p(e,t,!0);return n.onError.emit(a),console.warn(a),O(e)}))),o||(o=O(e)),o}(o,t)||Promise.resolve(void 0);return l.set(r,g),{new:!0,promise:g,keyObject:o,cacheKey:r}}));g.notify(),c.notify();const r=await Promise.all(o.map((e=>e.promise)));return o.forEach(((e,n)=>{const t=l.get(e.cacheKey)!==e.promise;if(e.new&&!t){l.delete(e.cacheKey);const t=r[n];t?L.addRecord(e.keyObject,t):L.getRecord(e.keyObject)||L.addRecord(e.keyObject,{})}})),g.notify(),c.notify(),o.map((e=>L.getRecord(e.keyObject)))},getAllRecords:()=>Array.from(u.entries()).map((([e,n])=>Object.assign(Object.assign({},m(e)),{data:n.data})))});return L}function L(e,n){var t={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&n.indexOf(a)<0&&(t[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(a=Object.getOwnPropertySymbols(e);i<a.length;i++)n.indexOf(a[i])<0&&Object.prototype.propertyIsEnumerable.call(e,a[i])&&(t[a[i]]=e[a[i]])}return t}const y="invalid",j={defaultNs:"",observerOptions:{tagAttributes:{textarea:["placeholder"],input:["value","placeholder"],img:["alt"],"*":["aria-label","title"]},restrictedElements:["script","style"],highlightKeys:["Alt"],highlightColor:"rgb(255, 0, 0)",highlightWidth:5,inputPrefix:"%-%tolgee:",inputSuffix:"%-%",passToParent:["option","optgroup"],fullKeyEncode:!1},observerType:"invisible",onFormatError:y,apiUrl:"https://app.tolgee.io",fetch:l(),onTranslationMissing:({key:e})=>e},k=(...e)=>{let n={};return e.forEach((e=>{n=Object.assign(Object.assign(Object.assign({},n),e),{observerOptions:Object.assign(Object.assign({},n.observerOptions),null==e?void 0:e.observerOptions)})})),n};function E(e,n){const t=k(j,null==n?void 0:n.initialOptions,e);return t.apiUrl=g(t.apiUrl),(null==e?void 0:e.fetch)&&(t.fetch=l(e.fetch)),{initialOptions:t,activeNamespaces:(null==n?void 0:n.activeNamespaces)||new Map,language:null==n?void 0:n.language,pendingLanguage:null==n?void 0:n.language,isInitialLoading:!1,isRunning:!1}}function w(e,a,i,o,r,s,g,c){const l={ui:void 0},u={formatters:[],finalFormatter:void 0,observer:void 0,devBackend:void 0,backends:[],ui:void 0,languageDetector:void 0,languageStorage:void 0},d=async({keysAndDefaults:e,event:n})=>{var t;const a=e.map((({key:e,ns:n,defaultValue:t})=>({key:e,defaultValue:t,fallbackNamespaces:o(n),namespace:r({key:e,ns:n})[0],translation:s({key:e,ns:n})})));null===(t=u.ui)||void 0===t||t.handleElementClick(a,n)},p=(e,n)=>{var t;return(null===(t=u.observer)||void 0===t?void 0:t.findPositions(e,n))||[]};function h(e){const n=s({key:e.key,ns:e.ns});return C.formatTranslation(Object.assign(Object.assign({},e),{translation:n,formatEnabled:!0}))}function m(){return{fetch:a().fetch}}function b(e){u.observer=null==e?void 0:e()}function O(){return Boolean(u.observer)}function j(e){e&&u.formatters.push(e)}function k(e){u.finalFormatter=e}function E(e){l.ui=e}function w(){return Boolean(l.ui)}function R(e){u.languageStorage=e}function N(e){u.languageDetector=e}function D(e){e&&u.backends.push(e)}function F(e){u.devBackend=e}const C=Object.freeze({addPlugin:function(e,n){n(e,Object.freeze({setFinalFormatter:k,addFormatter:j,setObserver:b,hasObserver:O,setUi:E,hasUi:w,setDevBackend:F,addBackend:D,setLanguageDetector:N,setLanguageStorage:R}))},run(){var e,n;const{apiKey:t,apiUrl:i,projectId:o,observerOptions:r}=a();u.ui=null===(e=l.ui)||void 0===e?void 0:e.call(l,{apiKey:t,apiUrl:i,projectId:o,highlight:C.highlight,changeTranslation:g,findPositions:p,onPermanentChange:e=>c.onPermanentChange.emit(e)}),null===(n=u.observer)||void 0===n||n.run({mouseHighlight:!0,options:r,translate:h,onClick:d})},stop(){var e;u.ui=void 0,null===(e=u.observer)||void 0===e||e.stop()},getLanguageStorage:()=>u.languageStorage,getInitialLanguage(){const e=i();return n(t(c.onError,(e=>new v("Tolgee: Failed to load language",e)),(()=>{var e;return null===(e=u.languageStorage)||void 0===e?void 0:e.getLanguage(m())})),(n=>e&&!e.includes(n)||!n?function(){if(!u.languageDetector)return;const e=i();return t(c.onError,(e=>new f("Tolgee: Failed to detect language",e)),(()=>{var n;return null===(n=u.languageDetector)||void 0===n?void 0:n.getLanguage(Object.assign({availableLanguages:e},m()))}))}():n))},setStoredLanguage:e=>t(c.onError,(e=>new v("Tolgee: Failed to store language",e)),(()=>{var n;return null===(n=u.languageStorage)||void 0===n?void 0:n.setLanguage(e,m())})),getDevBackend:()=>u.devBackend,getBackendRecord:({language:e,namespace:n})=>{for(const t of u.backends){const a=t.getRecord(Object.assign({language:e,namespace:n},m()));if(void 0!==a)return a}},getBackendDevRecord:({language:e,namespace:n})=>{var t;const{apiKey:i,apiUrl:o,projectId:r}=a();return null===(t=u.devBackend)||void 0===t?void 0:t.getRecord(Object.assign({apiKey:i,apiUrl:o,projectId:r,language:e,namespace:n},m()))},getLanguageDetector:()=>u.languageDetector,retranslate(){var e;null===(e=u.observer)||void 0===e||e.retranslate()},highlight:(e,n)=>{var t,a;return(null===(a=null===(t=u.observer)||void 0===t?void 0:t.highlight)||void 0===a?void 0:a.call(t,e,n))||{unhighlight(){}}},unwrap(e){var n;return u.observer?null===(n=u.observer)||void 0===n?void 0:n.unwrap(e):{text:e,keys:[]}},wrap(e){var n;return u.observer?null===(n=u.observer)||void 0===n?void 0:n.wrap(e):e.translation},hasDevBackend:()=>Boolean(C.getDevBackend()),formatTranslation(n){var t,{formatEnabled:i}=n,o=L(n,["formatEnabled"]);const{key:r,translation:s,defaultValue:g,noWrap:c,params:l,ns:d,orEmpty:p}=o,f=null!=s?s:g;let v="";null==s&&(v=a().onTranslationMissing(o));let h=null!=f?f:p?"":v;const m=e(),b=i||!(null===(t=u.observer)||void 0===t?void 0:t.outputNotFormattable),O=e=>u.observer&&!c?u.observer.wrap({key:r,translation:e,defaultValue:g,params:l,ns:d}):e;h=O(h);try{if(f&&m&&b)for(const e of u.formatters)h=e.format({translation:h,language:m,params:l});u.finalFormatter&&f&&m&&b&&(h=u.finalFormatter.format({translation:h,language:m,params:l}))}catch(e){console.error(e);const n=("string"==typeof(j=e)?j:"string"==typeof(null==j?void 0:j.message)?j.message:void 0)||y,t=a().onFormatError,i=typeof t;h="string"===i?t:"function"===i?t(n,o):y,h=O(h)}var j;return h}});return C}const R=(e,n,t)=>{let a=e;return Object.freeze({init(e){a=e},notify(){const e=n();a!==e&&t(e),a=e}})};const N=(e,...n)=>{let t,a={};return"object"==typeof e?a=e:(a.key=e,"string"==typeof n[0]?(a.defaultValue=n[0],t=n[1]):"object"==typeof n[0]&&(t=n[0])),t&&(a=Object.assign(Object.assign({},function(e){var{ns:n,noWrap:t,orEmpty:a,params:i,language:o}=e,r=L(e,["ns","noWrap","orEmpty","params","language"]);const s={ns:n,noWrap:t,orEmpty:a,language:o};return Object.assign(Object.assign({},s),{params:Object.assign({},r)})}(t)),a)),a};function D({options:t}){const i=function(e,n){let t=!0;function a(){return t}const i=Object.freeze({onPendingLanguageChange:u(a),onLanguageChange:u(a),onLoadingChange:u(a),onFetchingChange:u(a),onInitialLoaded:u(a),onRunningChange:u(a),onCacheChange:u(a),onUpdate:d(a,e,n),onPermanentChange:u(a),onError:u(a),setEmitterActive(e){t=e},on:(e,n)=>{switch(e){case"pendingLanguage":return i.onPendingLanguageChange.listen(n);case"language":return i.onLanguageChange.listen(n);case"loading":return i.onLoadingChange.listen(n);case"fetching":return i.onFetchingChange.listen(n);case"initialLoad":return i.onInitialLoaded.listen(n);case"running":return i.onRunningChange.listen(n);case"cache":return i.onCacheChange.listen(n);case"update":return i.onUpdate.listen(n);case"permanentChange":return i.onPermanentChange.listen(n);case"error":return i.onError.listen(n)}}});return i.onInitialLoaded.listen((()=>i.onUpdate.emit())),i.onLanguageChange.listen((()=>i.onUpdate.emit())),i.onCacheChange.listen((({value:e})=>i.onUpdate.emit([e.namespace],!0))),i}(b,L),c=R(!1,(()=>v.isFetching()),i.onFetchingChange.emit),l=R(!1,(()=>I.isLoading()),i.onLoadingChange.emit),p=function(e,n,t){let a,i=E();const c=Object.freeze({init(e){i=E(e,i)},isRunning:()=>i.isRunning,setRunning(e){i.isRunning!==e&&(i.isRunning=e,t.emit(e))},isInitialLoading:()=>i.isInitialLoading,setInitialLoading(e){i.isInitialLoading=e},getLanguage:()=>i.language||i.initialOptions.language,setLanguage(n){i.language!==n&&(i.language=n,e.emit(n))},getPendingLanguage:()=>i.pendingLanguage||c.getLanguage(),setPendingLanguage(e){i.pendingLanguage!==e&&(i.pendingLanguage=e,n.emit(e))},getInitialOptions:()=>Object.assign(Object.assign({},i.initialOptions),a),addActiveNs(e){o(e).forEach((e=>{const n=i.activeNamespaces.get(e);void 0!==n?i.activeNamespaces.set(e,n+1):i.activeNamespaces.set(e,1)}))},removeActiveNs(e){o(e).forEach((e=>{const n=i.activeNamespaces.get(e);void 0!==n&&n>1?i.activeNamespaces.set(e,n-1):i.activeNamespaces.delete(e)}))},getRequiredNamespaces:()=>s([...i.initialOptions.ns||[i.initialOptions.defaultNs],...o(i.initialOptions.fallbackNs),...i.activeNamespaces.keys()]),getFallbackLangs(e){const n=e||c.getLanguage();return n?s([n,...r(n,i.initialOptions.fallbackLanguage)]):[]},getFallbackNs:()=>o(i.initialOptions.fallbackNs),getDefaultNs:e=>void 0===e?i.initialOptions.defaultNs:e,getAvailableLanguages(){if(i.initialOptions.availableLanguages)return i.initialOptions.availableLanguages;if(i.initialOptions.staticData){const e=Object.keys(i.initialOptions.staticData).map((e=>m(e).language));return Array.from(new Set(e))}},withDefaultNs:e=>({namespace:void 0===e.namespace?c.getInitialOptions().defaultNs:e.namespace,language:e.language}),overrideCredentials(e){a=e?Object.assign(Object.assign({},e),{apiUrl:g(e.apiUrl)}):void 0}});return c}(i.onLanguageChange,i.onPendingLanguageChange,i.onRunningChange),f=w(p.getLanguage,p.getInitialOptions,p.getAvailableLanguages,y,C,S,k,i),v=O(i,f.getBackendRecord,f.getBackendDevRecord,p.withDefaultNs,p.isInitialLoading,c,l);let h;function b(){return p.getFallbackNs()}function L(e){return p.getDefaultNs(e)}function y(e){return[...o(L(e)),...b()]}function j(e){return[...o(null!=e?e:L()),...p.getRequiredNamespaces()]}function k(e,n,t){const a=p.withDefaultNs(e),i=v.getTranslation(a,n);return v.changeTranslation(a,n,t),{revert(){v.changeTranslation(a,n,i)}}}function D(e){p.init(e),v.addStaticData(p.getInitialOptions().staticData)}function F(e,t){const a=function(e,n){const t=p.getFallbackLangs(e),a=j(n),i=[];return t.forEach((e=>{a.forEach((n=>{v.exists({language:e,namespace:n},!0)||i.push({language:e,namespace:n})}))})),i}(e,t);if(a.length)return n(I.loadRecords(a),(()=>{}))}function C({key:e,ns:n}){const t=p.getFallbackLangs(),a=y(null!=n?n:void 0);return v.getTranslationNs(a,t,e)}function S({key:e,ns:n,language:t}){const a=y(null!=n?n:void 0),i=p.getFallbackLangs(t);return v.getTranslationFallback(a,i,e)}function A(){const t=n(function(){if(p.getLanguage())return;return n(f.getInitialLanguage(),(e=>{const n=e||p.getInitialOptions().defaultLanguage;n&&p.setLanguage(n)}))}(),(()=>F()));if(e(t))return p.setInitialLoading(!0),c.notify(),l.notify(),Promise.resolve(t).then((()=>{p.setInitialLoading(!1),c.notify(),l.notify(),i.onInitialLoaded.emit()}));i.onInitialLoaded.emit()}t&&D(t),i.onUpdate.listen((()=>{p.isRunning()&&f.retranslate()}));const I=Object.freeze(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},i),p),f),v),{init:D,getTranslation:S,changeTranslation:k,getTranslationNs:C,getDefaultAndFallbackNs:y,async changeLanguage(e){p.getPendingLanguage()===e&&p.getLanguage()===e||(p.setPendingLanguage(e),p.isRunning()&&await F(e),e===p.getPendingLanguage()&&(p.setLanguage(e),await f.setStoredLanguage(e)))},async addActiveNs(e,n){n||p.addActiveNs(e),p.isRunning()&&await F(void 0,e)},loadRecords:e=>v.loadRecords(e,I.isDev()),loadRecord:async e=>(await I.loadRecords([e]))[0],isLoading:e=>v.isLoading(p.getLanguage(),e),isLoaded(e){const n=p.getLanguage();if(!n)return!1;const t=p.getFallbackLangs(n),a=j(e),i=[];return t.forEach((e=>{a.forEach((n=>{v.exists({language:e,namespace:n})||i.push({language:e,namespace:n})}))})),0===i.length},t:(...e)=>{const n=N(...e),t=S(n);return f.formatTranslation(Object.assign(Object.assign({},n),{translation:t}))},isDev:()=>Boolean(p.getInitialOptions().apiKey&&p.getInitialOptions().apiUrl),run:()=>(function(){if((f.getLanguageDetector()||f.getLanguageStorage())&&!p.getAvailableLanguages())throw new Error(a("availableLanguages"));if(!p.getLanguage()&&!p.getInitialOptions().defaultLanguage)throw new Error(a(["defaultLanguage","language"]))}(),p.isRunning()||(p.setRunning(!0),f.run(),h=A()),Promise.resolve(h)),stop(){p.isRunning()&&(f.stop(),p.setRunning(!1))}}));return I}const F=0,C=1,S=2;class A extends Error{constructor(e,n,t){let a;a=e===F?"Empty parameter":e===C?"Unexpected character":"Unexpected end",super(`Tolgee parser: ${a} at ${n} in "${t}"`),this.code=e,this.index=n}}function I(e){return/\s/.test(e)}const T=0,P=1,x=2,U=3,B=4,z=new Set([x,P,T]),K="'",$=new Set(["{","}",K]),M=e=>/[0-9a-zA-Z_]/.test(e);function V(e,n){const[t,a]=function(e){let n=T,t="",a="",i="";const o=[],r=[];let s=0;function g(n){throw new A(n,s,e)}const c=()=>{o.push(t),t=""},l=()=>{""===a&&g(F),r.push(a),a=""};for(s=0;s<e.length;s++)switch(i=e[s],n){case T:i===K?(t+=i,n=P):"{"===i?(c(),n=U):(t+=i,n=T);break;case P:$.has(i)?(t=t.slice(0,-1)+i,n=x):(t+=i,n=T);break;case x:i===K?n=T:(t+=i,n=x);break;case U:"}"===i?(l(),n=T):I(i)?""!==a&&(l(),n=B):(M(i)||g(C),a+=i,n=U);break;case B:"}"==i?n=T:I(i)?n=B:g(C)}return z.has(n)||g(S),c(),[o,r]}(e),i=[t[0]];for(let o=1;o<t.length;o++){const r=null==n?void 0:n[a[o-1]];if(void 0===r)throw new Error(`Missing parameter "${a[o-1]}" in "${e}"`);i.push(String(r)),i.push(t[o])}return i.join("")}exports.FormatSimple=()=>(e,n)=>(n.setFinalFormatter({format:({translation:e,params:n})=>V(e,n)}),e),exports.LanguageDetectorError=f,exports.LanguageStorageError=v,exports.RecordFetchError=p,exports.TolgeeCore=()=>{const e={plugins:[],options:{}},n=Object.freeze({use:t=>(e.plugins.push(t),n),updateDefaults:t=>(e.options=k(e.options,t),n),init(n){const t=function(e){const n=D({options:e});function t(e){const t=n.isRunning();t&&n.stop(),e(),n.isDev()&&n.invalidate(),t&&n.run()}n.isDev()&&n.invalidate();const a=Object.freeze({on:n.on,onNsUpdate:n.onUpdate.listenSome,setEmitterActive:n.setEmitterActive,getLanguage:n.getLanguage,getPendingLanguage:n.getPendingLanguage,changeLanguage:n.changeLanguage,changeTranslation:n.changeTranslation,addActiveNs:n.addActiveNs,removeActiveNs:n.removeActiveNs,loadRecords:n.loadRecords,loadRecord:n.loadRecord,addStaticData:n.addStaticData,getRecord:n.getRecord,getAllRecords:n.getAllRecords,isLoaded:n.isLoaded,isInitialLoading:n.isInitialLoading,isLoading:n.isLoading,isFetching:n.isFetching,isRunning:n.isRunning,run:n.run,stop:n.stop,t:n.t,highlight:n.highlight,getInitialOptions:n.getInitialOptions,isDev:n.isDev,wrap:n.wrap,unwrap:n.unwrap,overrideCredentials(e){t((()=>n.overrideCredentials(e)))},addPlugin(e){e&&t((()=>n.addPlugin(a,e)))},updateOptions(e){e&&t((()=>n.init(e)))}});return a}(k(e.options,n));return e.plugins.forEach(t.addPlugin),t}});return n},exports.createFetchFunction=l,exports.getFallback=i,exports.getFallbackArray=o,exports.getTranslateProps=N; | ||
//# sourceMappingURL=tolgee.cjs.min.js.map |
@@ -12,2 +12,21 @@ function isPromise(value) { | ||
} | ||
function handleRegularOrAsyncErr(onError, createError, callback) { | ||
function handle(e) { | ||
const error = createError(e); | ||
onError.emit(error); | ||
// eslint-disable-next-line no-console | ||
console.error(error); | ||
throw error; | ||
} | ||
try { | ||
const result = callback(); | ||
if (isPromise(result)) { | ||
return result.catch(handle); | ||
} | ||
return result; | ||
} | ||
catch (e) { | ||
handle(e); | ||
} | ||
} | ||
function missingOptionError(option) { | ||
@@ -187,2 +206,3 @@ const options = (Array.isArray(option) ? option : [option]).map((val) => `'${val}'`); | ||
onPermanentChange: EventEmitter(isActive), | ||
onError: EventEmitter(isActive), | ||
setEmitterActive(active) { | ||
@@ -211,2 +231,4 @@ emitterActive = active; | ||
return self.onPermanentChange.listen(handler); | ||
case 'error': | ||
return self.onError.listen(handler); | ||
} | ||
@@ -221,2 +243,28 @@ }), | ||
class RecordFetchError extends Error { | ||
constructor(descriptor, cause, isDev = false) { | ||
const { language, namespace } = descriptor; | ||
super(`Tolgee: Failed to fetch record for "${language}"${namespace && ` and "${namespace}"`}`); | ||
this.cause = cause; | ||
this.isDev = isDev; | ||
this.name = 'RecordFetchError'; | ||
this.language = language; | ||
this.namespace = namespace; | ||
} | ||
} | ||
class LanguageDetectorError extends Error { | ||
constructor(message, cause) { | ||
super(message); | ||
this.cause = cause; | ||
this.name = 'LanguageDetectorError'; | ||
} | ||
} | ||
class LanguageStorageError extends Error { | ||
constructor(message, cause) { | ||
super(message); | ||
this.cause = cause; | ||
this.name = 'LanguageStorageError'; | ||
} | ||
} | ||
const flattenTranslations = (data) => { | ||
@@ -254,3 +302,3 @@ const result = new Map(); | ||
function Cache(onCacheChange, backendGetRecord, backendGetDevRecord, withDefaultNs, isInitialLoading, fetchingObserver, loadingObserver) { | ||
function Cache(events, backendGetRecord, backendGetDevRecord, withDefaultNs, isInitialLoading, fetchingObserver, loadingObserver) { | ||
const asyncRequests = new Map(); | ||
@@ -266,3 +314,3 @@ const cache = new Map(); | ||
}); | ||
onCacheChange.emit(descriptor); | ||
events.onCacheChange.emit(descriptor); | ||
} | ||
@@ -273,21 +321,34 @@ /** | ||
function fetchProd(keyObject) { | ||
let dataPromise = undefined; | ||
if (!dataPromise) { | ||
let dataOrPromise = undefined; | ||
if (!dataOrPromise) { | ||
const staticDataValue = staticData[encodeCacheKey(keyObject)]; | ||
if (typeof staticDataValue === 'function') { | ||
dataPromise = staticDataValue(); | ||
dataOrPromise = staticDataValue(); | ||
} | ||
} | ||
if (!dataPromise) { | ||
dataPromise = backendGetRecord(keyObject); | ||
if (!dataOrPromise) { | ||
dataOrPromise = backendGetRecord(keyObject); | ||
} | ||
return dataPromise; | ||
if (isPromise(dataOrPromise)) { | ||
return dataOrPromise === null || dataOrPromise === void 0 ? void 0 : dataOrPromise.catch((e) => { | ||
const error = new RecordFetchError(keyObject, e); | ||
events.onError.emit(error); | ||
// eslint-disable-next-line no-console | ||
console.error(error); | ||
throw error; | ||
}); | ||
} | ||
else { | ||
return dataOrPromise; | ||
} | ||
} | ||
function fetchData(keyObject, isDev) { | ||
var _a; | ||
let dataPromise = undefined; | ||
let dataOrPromise = undefined; | ||
if (isDev) { | ||
dataPromise = (_a = backendGetDevRecord(keyObject)) === null || _a === void 0 ? void 0 : _a.catch(() => { | ||
dataOrPromise = (_a = backendGetDevRecord(keyObject)) === null || _a === void 0 ? void 0 : _a.catch((e) => { | ||
const error = new RecordFetchError(keyObject, e, true); | ||
events.onError.emit(error); | ||
// eslint-disable-next-line no-console | ||
console.warn(`Tolgee: Failed to fetch data from dev backend`); | ||
console.warn(error); | ||
// fallback to prod fetch if dev fails | ||
@@ -297,6 +358,6 @@ return fetchProd(keyObject); | ||
} | ||
if (!dataPromise) { | ||
dataPromise = fetchProd(keyObject); | ||
if (!dataOrPromise) { | ||
dataOrPromise = fetchProd(keyObject); | ||
} | ||
return dataPromise; | ||
return dataOrPromise; | ||
} | ||
@@ -370,3 +431,3 @@ const self = Object.freeze({ | ||
record === null || record === void 0 ? void 0 : record.set(key, value); | ||
onCacheChange.emit(Object.assign(Object.assign({}, descriptor), { key })); | ||
events.onCacheChange.emit(Object.assign(Object.assign({}, descriptor), { key })); | ||
}, | ||
@@ -531,3 +592,3 @@ isFetching(ns) { | ||
function Plugins(getLanguage, getInitialOptions, getAvailableLanguages, getFallbackNamespaces, getTranslationNs, getTranslation, changeTranslation, onPermanentChange) { | ||
function Plugins(getLanguage, getInitialOptions, getAvailableLanguages, getFallbackNamespaces, getTranslationNs, getTranslation, changeTranslation, events) { | ||
const plugins = { | ||
@@ -602,2 +663,5 @@ ui: undefined, | ||
} | ||
function storageLoadLanguage() { | ||
return handleRegularOrAsyncErr(events.onError, (e) => new LanguageStorageError('Tolgee: Failed to load language', e), () => { var _a; return (_a = instances.languageStorage) === null || _a === void 0 ? void 0 : _a.getLanguage(getCommonProps()); }); | ||
} | ||
function detectLanguage() { | ||
@@ -608,3 +672,6 @@ if (!instances.languageDetector) { | ||
const availableLanguages = getAvailableLanguages(); | ||
return instances.languageDetector.getLanguage(Object.assign({ availableLanguages }, getCommonProps())); | ||
return handleRegularOrAsyncErr(events.onError, (e) => new LanguageDetectorError('Tolgee: Failed to detect language', e), () => { | ||
var _a; | ||
return (_a = instances.languageDetector) === null || _a === void 0 ? void 0 : _a.getLanguage(Object.assign({ availableLanguages }, getCommonProps())); | ||
}); | ||
} | ||
@@ -646,3 +713,3 @@ function addBackend(backend) { | ||
findPositions, | ||
onPermanentChange, | ||
onPermanentChange: (data) => events.onPermanentChange.emit(data), | ||
}); | ||
@@ -665,5 +732,4 @@ (_b = instances.observer) === null || _b === void 0 ? void 0 : _b.run({ | ||
getInitialLanguage() { | ||
var _a; | ||
const availableLanguages = getAvailableLanguages(); | ||
const languageOrPromise = (_a = instances.languageStorage) === null || _a === void 0 ? void 0 : _a.getLanguage(getCommonProps()); | ||
const languageOrPromise = storageLoadLanguage(); | ||
return valueOrPromise(languageOrPromise, (language) => { | ||
@@ -678,4 +744,3 @@ if ((!availableLanguages || availableLanguages.includes(language)) && | ||
setStoredLanguage(language) { | ||
var _a; | ||
(_a = instances.languageStorage) === null || _a === void 0 ? void 0 : _a.setLanguage(language, getCommonProps()); | ||
return handleRegularOrAsyncErr(events.onError, (e) => new LanguageStorageError('Tolgee: Failed to store language', e), () => { var _a; return (_a = instances.languageStorage) === null || _a === void 0 ? void 0 : _a.setLanguage(language, getCommonProps()); }); | ||
}, | ||
@@ -689,9 +754,2 @@ getDevBackend() { | ||
namespace }, getCommonProps())); | ||
if (isPromise(data)) { | ||
return data === null || data === void 0 ? void 0 : data.catch((e) => { | ||
// eslint-disable-next-line no-console | ||
console.error(e); | ||
return {}; | ||
}); | ||
} | ||
if (data !== undefined) { | ||
@@ -985,4 +1043,4 @@ return data; | ||
const state = State(events.onLanguageChange, events.onPendingLanguageChange, events.onRunningChange); | ||
const pluginService = Plugins(state.getLanguage, state.getInitialOptions, state.getAvailableLanguages, getDefaultAndFallbackNs, getTranslationNs, getTranslation, changeTranslation, onPermanentChange); | ||
const cache = Cache(events.onCacheChange, pluginService.getBackendRecord, pluginService.getBackendDevRecord, state.withDefaultNs, state.isInitialLoading, fetchingObserver, loadingObserver); | ||
const pluginService = Plugins(state.getLanguage, state.getInitialOptions, state.getAvailableLanguages, getDefaultAndFallbackNs, getTranslationNs, getTranslation, changeTranslation, events); | ||
const cache = Cache(events, pluginService.getBackendRecord, pluginService.getBackendDevRecord, state.withDefaultNs, state.isInitialLoading, fetchingObserver, loadingObserver); | ||
if (options) { | ||
@@ -1026,8 +1084,2 @@ init(options); | ||
} | ||
function onPermanentChange(props) { | ||
events.onPermanentChange.emit({ | ||
key: props.key, | ||
namespace: props.namespace, | ||
}); | ||
} | ||
function init(options) { | ||
@@ -1123,3 +1175,3 @@ state.init(options); | ||
state.setLanguage(language); | ||
pluginService.setStoredLanguage(language); | ||
await pluginService.setStoredLanguage(language); | ||
} | ||
@@ -1556,3 +1608,3 @@ }, | ||
export { FormatSimple, TolgeeCore, createFetchFunction, getFallback, getFallbackArray, getTranslateProps }; | ||
export { FormatSimple, LanguageDetectorError, LanguageStorageError, RecordFetchError, TolgeeCore, createFetchFunction, getFallback, getFallbackArray, getTranslateProps }; | ||
//# sourceMappingURL=tolgee.esm.js.map |
@@ -1,2 +0,2 @@ | ||
function e(e){return Boolean(e&&"function"==typeof e.then)}function n(n,t){return e(n)?Promise.resolve(n).then(t):t(n)}function t(e){const n=(Array.isArray(e)?e:[e]).map((e=>`'${e}'`)),t=n.slice(-2).join(" or ");return`Tolgee: You need to specify ${[...n.slice(0,-2),t].join(", ")} option`}function a(e){return"string"==typeof e?[e]:Array.isArray(e)?e:void 0}function i(e){return a(e)||[]}function o(e,n){return"object"!=typeof(t=n)||Array.isArray(t)||null===t?i(n):i(null==n?void 0:n[e]);var t}function s(e){return Array.from(new Set(e))}function r(e){return e?e.replace(/\/+$/,""):e}const g=(e,n)=>fetch(e,n),c=(e=g)=>(n,t)=>e(n,Object.assign(Object.assign({},t),{headers:Object.assign({"X-Tolgee-SDK-Type":"JS","X-Tolgee-SDK-Version":process.env.TOLGEE_UI_VERSION||"prerelease"},null==t?void 0:t.headers)}));function l(e){let n=[];return Object.freeze({listen(e){const t=n=>{e(n)};return n.push(t),{unsubscribe(){n=n.filter((e=>t!==e))}}},emit(t){e()&&n.forEach((e=>e({value:t})))}})}function u(e,n,t){const a=new Set,o=new Set;let s=[];function r(){if(0===s.length)return;const e=s;s=[],a.forEach((e=>{e({value:void 0})}));let t=new Set;e.forEach((e=>{void 0===e?t=void 0:void 0!==t&&e.forEach((e=>t.add(e)))}));!function(e){const t=new Set(n());o.forEach((n=>{(void 0===e||-1!==(null==e?void 0:e.findIndex((e=>t.has(e)||n.namespaces.has(e)))))&&n.fn({value:void 0})}))}(t?Array.from(t.keys()):void 0)}return Object.freeze({emit(n,t){e()&&(s.push(n),t?setTimeout(r,0):r())},listen(e){a.add(e);return{unsubscribe:()=>{a.delete(e)}}},listenSome(e){const n={fn:n=>{e(n)},namespaces:new Set};o.add(n);const a={unsubscribe:()=>{o.delete(n)},subscribeNs:e=>(i(e).forEach((e=>n.namespaces.add(e))),void 0===e&&n.namespaces.add(t()),a)};return a}})}const d=e=>{const n=new Map;return Object.entries(e).forEach((([e,t])=>{null!=t&&("object"!=typeof t?n.set(e,t):d(t).forEach(((t,a)=>{n.set(e+"."+a,t)})))})),n},p=e=>{const[n,...t]=e.split(":");return{language:n,namespace:t.join(":")||""}},f=({language:e,namespace:n})=>n?`${e}:${n}`:e;function v(e,n,t,a,o,r,g){const c=new Map,l=new Map;let u={},v=0;function h(n,t,a){const i=f(n);l.set(i,{data:d(t),version:a}),e.emit(n)}function m(e){let t;if(!t){const n=u[f(e)];"function"==typeof n&&(t=n())}return t||(t=n(e)),t}const b=Object.freeze({addStaticData(e){e&&(u=Object.assign(Object.assign({},u),e),Object.entries(e).forEach((([e,n])=>{if("function"!=typeof n){const t=p(e),a=l.get(e);a&&0!==a.version||h(t,n,0)}})))},invalidate(){c.clear(),v+=1},addRecord(e,n){h(e,n,v)},exists(e,n=!1){const t=l.get(f(e));return t&&n?t.version===v:Boolean(t)},getRecord(e){var n;return null===(n=l.get(f(a(e))))||void 0===n?void 0:n.data},getTranslation(e,n){var t;return null===(t=l.get(f(e)))||void 0===t?void 0:t.data.get(n)},getTranslationNs(e,n,t){var a;for(const i of e)for(const e of n){const n=null===(a=l.get(f({language:e,namespace:i})))||void 0===a?void 0:a.data.get(t);if(null!=n)return[i]}return s(e)},getTranslationFallback(e,n,t){var a;for(const i of e)for(const e of n){const n=null===(a=l.get(f({language:e,namespace:i})))||void 0===a?void 0:a.data.get(t);if(null!=n)return n}},changeTranslation(n,t,a){var i;const o=null===(i=l.get(f(n)))||void 0===i?void 0:i.data;null==o||o.set(t,a),e.emit(Object.assign(Object.assign({},n),{key:t}))},isFetching(e){if(o())return!0;if(void 0===e)return c.size>0;const n=i(e);return Boolean(Array.from(c.keys()).find((e=>n.includes(p(e).namespace))))},isLoading(e,n){const t=i(n);return Boolean(o()||Array.from(c.keys()).find((n=>{const a=p(n);return(!t.length||t.includes(a.namespace))&&!b.exists({namespace:a.namespace,language:e})})))},async loadRecords(e,n){const i=e.map((e=>{const i=a(e),o=f(i),s=c.get(o);if(s)return{new:!1,promise:s,keyObject:i,cacheKey:o};const r=function(e,n){var a;let i;return n&&(i=null===(a=t(e))||void 0===a?void 0:a.catch((()=>(console.warn("Tolgee: Failed to fetch data from dev backend"),m(e))))),i||(i=m(e)),i}(i,n)||Promise.resolve(void 0);return c.set(o,r),{new:!0,promise:r,keyObject:i,cacheKey:o}}));r.notify(),g.notify();const o=await Promise.all(i.map((e=>e.promise)));return i.forEach(((e,n)=>{const t=c.get(e.cacheKey)!==e.promise;if(e.new&&!t){c.delete(e.cacheKey);const t=o[n];t?b.addRecord(e.keyObject,t):b.getRecord(e.keyObject)||b.addRecord(e.keyObject,{})}})),r.notify(),g.notify(),i.map((e=>b.getRecord(e.keyObject)))},getAllRecords:()=>Array.from(l.entries()).map((([e,n])=>Object.assign(Object.assign({},p(e)),{data:n.data})))});return b}function h(e,n){var t={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&n.indexOf(a)<0&&(t[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(a=Object.getOwnPropertySymbols(e);i<a.length;i++)n.indexOf(a[i])<0&&Object.prototype.propertyIsEnumerable.call(e,a[i])&&(t[a[i]]=e[a[i]])}return t}const m="invalid",b={defaultNs:"",observerOptions:{tagAttributes:{textarea:["placeholder"],input:["value","placeholder"],img:["alt"],"*":["aria-label","title"]},restrictedElements:["script","style"],highlightKeys:["Alt"],highlightColor:"rgb(255, 0, 0)",highlightWidth:5,inputPrefix:"%-%tolgee:",inputSuffix:"%-%",passToParent:["option","optgroup"],fullKeyEncode:!1},observerType:"invisible",onFormatError:m,apiUrl:"https://app.tolgee.io",fetch:c(),onTranslationMissing:({key:e})=>e},O=(...e)=>{let n={};return e.forEach((e=>{n=Object.assign(Object.assign(Object.assign({},n),e),{observerOptions:Object.assign(Object.assign({},n.observerOptions),null==e?void 0:e.observerOptions)})})),n};function y(e,n){const t=O(b,null==n?void 0:n.initialOptions,e);return t.apiUrl=r(t.apiUrl),(null==e?void 0:e.fetch)&&(t.fetch=c(e.fetch)),{initialOptions:t,activeNamespaces:(null==n?void 0:n.activeNamespaces)||new Map,language:null==n?void 0:n.language,pendingLanguage:null==n?void 0:n.language,isInitialLoading:!1,isRunning:!1}}function L(t,a,i,o,s,r,g,c){const l={ui:void 0},u={formatters:[],finalFormatter:void 0,observer:void 0,devBackend:void 0,backends:[],ui:void 0,languageDetector:void 0,languageStorage:void 0},d=async({keysAndDefaults:e,event:n})=>{var t;const a=e.map((({key:e,ns:n,defaultValue:t})=>({key:e,defaultValue:t,fallbackNamespaces:o(n),namespace:s({key:e,ns:n})[0],translation:r({key:e,ns:n})})));null===(t=u.ui)||void 0===t||t.handleElementClick(a,n)},p=(e,n)=>{var t;return(null===(t=u.observer)||void 0===t?void 0:t.findPositions(e,n))||[]};function f(e){const n=r({key:e.key,ns:e.ns});return D.formatTranslation(Object.assign(Object.assign({},e),{translation:n,formatEnabled:!0}))}function v(){return{fetch:a().fetch}}function b(e){u.observer=null==e?void 0:e()}function O(){return Boolean(u.observer)}function y(e){e&&u.formatters.push(e)}function L(e){u.finalFormatter=e}function j(e){l.ui=e}function k(){return Boolean(l.ui)}function R(e){u.languageStorage=e}function w(e){u.languageDetector=e}function E(e){e&&u.backends.push(e)}function N(e){u.devBackend=e}const D=Object.freeze({addPlugin:function(e,n){n(e,Object.freeze({setFinalFormatter:L,addFormatter:y,setObserver:b,hasObserver:O,setUi:j,hasUi:k,setDevBackend:N,addBackend:E,setLanguageDetector:w,setLanguageStorage:R}))},run(){var e,n;const{apiKey:t,apiUrl:i,projectId:o,observerOptions:s}=a();u.ui=null===(e=l.ui)||void 0===e?void 0:e.call(l,{apiKey:t,apiUrl:i,projectId:o,highlight:D.highlight,changeTranslation:g,findPositions:p,onPermanentChange:c}),null===(n=u.observer)||void 0===n||n.run({mouseHighlight:!0,options:s,translate:f,onClick:d})},stop(){var e;u.ui=void 0,null===(e=u.observer)||void 0===e||e.stop()},getLanguageStorage:()=>u.languageStorage,getInitialLanguage(){var e;const t=i();return n(null===(e=u.languageStorage)||void 0===e?void 0:e.getLanguage(v()),(e=>t&&!t.includes(e)||!e?function(){if(!u.languageDetector)return;const e=i();return u.languageDetector.getLanguage(Object.assign({availableLanguages:e},v()))}():e))},setStoredLanguage(e){var n;null===(n=u.languageStorage)||void 0===n||n.setLanguage(e,v())},getDevBackend:()=>u.devBackend,getBackendRecord:({language:n,namespace:t})=>{for(const a of u.backends){const i=a.getRecord(Object.assign({language:n,namespace:t},v()));if(e(i))return null==i?void 0:i.catch((e=>(console.error(e),{})));if(void 0!==i)return i}},getBackendDevRecord:({language:e,namespace:n})=>{var t;const{apiKey:i,apiUrl:o,projectId:s}=a();return null===(t=u.devBackend)||void 0===t?void 0:t.getRecord(Object.assign({apiKey:i,apiUrl:o,projectId:s,language:e,namespace:n},v()))},getLanguageDetector:()=>u.languageDetector,retranslate(){var e;null===(e=u.observer)||void 0===e||e.retranslate()},highlight:(e,n)=>{var t,a;return(null===(a=null===(t=u.observer)||void 0===t?void 0:t.highlight)||void 0===a?void 0:a.call(t,e,n))||{unhighlight(){}}},unwrap(e){var n;return u.observer?null===(n=u.observer)||void 0===n?void 0:n.unwrap(e):{text:e,keys:[]}},wrap(e){var n;return u.observer?null===(n=u.observer)||void 0===n?void 0:n.wrap(e):e.translation},hasDevBackend:()=>Boolean(D.getDevBackend()),formatTranslation(e){var n,{formatEnabled:i}=e,o=h(e,["formatEnabled"]);const{key:s,translation:r,defaultValue:g,noWrap:c,params:l,ns:d,orEmpty:p}=o,f=null!=r?r:g;let v="";null==r&&(v=a().onTranslationMissing(o));let b=null!=f?f:p?"":v;const O=t(),y=i||!(null===(n=u.observer)||void 0===n?void 0:n.outputNotFormattable),L=e=>u.observer&&!c?u.observer.wrap({key:s,translation:e,defaultValue:g,params:l,ns:d}):e;b=L(b);try{if(f&&O&&y)for(const e of u.formatters)b=e.format({translation:b,language:O,params:l});u.finalFormatter&&f&&O&&y&&(b=u.finalFormatter.format({translation:b,language:O,params:l}))}catch(e){console.error(e);const n=("string"==typeof(j=e)?j:"string"==typeof(null==j?void 0:j.message)?j.message:void 0)||m,t=a().onFormatError,i=typeof t;b="string"===i?t:"function"===i?t(n,o):m,b=L(b)}var j;return b}});return D}const j=(e,n,t)=>{let a=e;return Object.freeze({init(e){a=e},notify(){const e=n();a!==e&&t(e),a=e}})};const k=(e,...n)=>{let t,a={};return"object"==typeof e?a=e:(a.key=e,"string"==typeof n[0]?(a.defaultValue=n[0],t=n[1]):"object"==typeof n[0]&&(t=n[0])),t&&(a=Object.assign(Object.assign({},function(e){var{ns:n,noWrap:t,orEmpty:a,params:i,language:o}=e,s=h(e,["ns","noWrap","orEmpty","params","language"]);const r={ns:n,noWrap:t,orEmpty:a,language:o};return Object.assign(Object.assign({},r),{params:Object.assign({},s)})}(t)),a)),a};function R({options:a}){const g=function(e,n){let t=!0;function a(){return t}const i=Object.freeze({onPendingLanguageChange:l(a),onLanguageChange:l(a),onLoadingChange:l(a),onFetchingChange:l(a),onInitialLoaded:l(a),onRunningChange:l(a),onCacheChange:l(a),onUpdate:u(a,e,n),onPermanentChange:l(a),setEmitterActive(e){t=e},on:(e,n)=>{switch(e){case"pendingLanguage":return i.onPendingLanguageChange.listen(n);case"language":return i.onLanguageChange.listen(n);case"loading":return i.onLoadingChange.listen(n);case"fetching":return i.onFetchingChange.listen(n);case"initialLoad":return i.onInitialLoaded.listen(n);case"running":return i.onRunningChange.listen(n);case"cache":return i.onCacheChange.listen(n);case"update":return i.onUpdate.listen(n);case"permanentChange":return i.onPermanentChange.listen(n)}}});return i.onInitialLoaded.listen((()=>i.onUpdate.emit())),i.onLanguageChange.listen((()=>i.onUpdate.emit())),i.onCacheChange.listen((({value:e})=>i.onUpdate.emit([e.namespace],!0))),i}(O,R),c=j(!1,(()=>m.isFetching()),g.onFetchingChange.emit),d=j(!1,(()=>F.isLoading()),g.onLoadingChange.emit),f=function(e,n,t){let a,g=y();const c=Object.freeze({init(e){g=y(e,g)},isRunning:()=>g.isRunning,setRunning(e){g.isRunning!==e&&(g.isRunning=e,t.emit(e))},isInitialLoading:()=>g.isInitialLoading,setInitialLoading(e){g.isInitialLoading=e},getLanguage:()=>g.language||g.initialOptions.language,setLanguage(n){g.language!==n&&(g.language=n,e.emit(n))},getPendingLanguage:()=>g.pendingLanguage||c.getLanguage(),setPendingLanguage(e){g.pendingLanguage!==e&&(g.pendingLanguage=e,n.emit(e))},getInitialOptions:()=>Object.assign(Object.assign({},g.initialOptions),a),addActiveNs(e){i(e).forEach((e=>{const n=g.activeNamespaces.get(e);void 0!==n?g.activeNamespaces.set(e,n+1):g.activeNamespaces.set(e,1)}))},removeActiveNs(e){i(e).forEach((e=>{const n=g.activeNamespaces.get(e);void 0!==n&&n>1?g.activeNamespaces.set(e,n-1):g.activeNamespaces.delete(e)}))},getRequiredNamespaces:()=>s([...g.initialOptions.ns||[g.initialOptions.defaultNs],...i(g.initialOptions.fallbackNs),...g.activeNamespaces.keys()]),getFallbackLangs(e){const n=e||c.getLanguage();return n?s([n,...o(n,g.initialOptions.fallbackLanguage)]):[]},getFallbackNs:()=>i(g.initialOptions.fallbackNs),getDefaultNs:e=>void 0===e?g.initialOptions.defaultNs:e,getAvailableLanguages(){if(g.initialOptions.availableLanguages)return g.initialOptions.availableLanguages;if(g.initialOptions.staticData){const e=Object.keys(g.initialOptions.staticData).map((e=>p(e).language));return Array.from(new Set(e))}},withDefaultNs:e=>({namespace:void 0===e.namespace?c.getInitialOptions().defaultNs:e.namespace,language:e.language}),overrideCredentials(e){a=e?Object.assign(Object.assign({},e),{apiUrl:r(e.apiUrl)}):void 0}});return c}(g.onLanguageChange,g.onPendingLanguageChange,g.onRunningChange),h=L(f.getLanguage,f.getInitialOptions,f.getAvailableLanguages,w,I,A,N,(function(e){g.onPermanentChange.emit({key:e.key,namespace:e.namespace})})),m=v(g.onCacheChange,h.getBackendRecord,h.getBackendDevRecord,f.withDefaultNs,f.isInitialLoading,c,d);let b;function O(){return f.getFallbackNs()}function R(e){return f.getDefaultNs(e)}function w(e){return[...i(R(e)),...O()]}function E(e){return[...i(null!=e?e:R()),...f.getRequiredNamespaces()]}function N(e,n,t){const a=f.withDefaultNs(e),i=m.getTranslation(a,n);return m.changeTranslation(a,n,t),{revert(){m.changeTranslation(a,n,i)}}}function D(e){f.init(e),m.addStaticData(f.getInitialOptions().staticData)}function C(e,t){const a=function(e,n){const t=f.getFallbackLangs(e),a=E(n),i=[];return t.forEach((e=>{a.forEach((n=>{m.exists({language:e,namespace:n},!0)||i.push({language:e,namespace:n})}))})),i}(e,t);if(a.length)return n(F.loadRecords(a),(()=>{}))}function I({key:e,ns:n}){const t=f.getFallbackLangs(),a=w(null!=n?n:void 0);return m.getTranslationNs(a,t,e)}function A({key:e,ns:n,language:t}){const a=w(null!=n?n:void 0),i=f.getFallbackLangs(t);return m.getTranslationFallback(a,i,e)}function S(){const t=n(function(){if(f.getLanguage())return;return n(h.getInitialLanguage(),(e=>{const n=e||f.getInitialOptions().defaultLanguage;n&&f.setLanguage(n)}))}(),(()=>C()));if(e(t))return f.setInitialLoading(!0),c.notify(),d.notify(),Promise.resolve(t).then((()=>{f.setInitialLoading(!1),c.notify(),d.notify(),g.onInitialLoaded.emit()}));g.onInitialLoaded.emit()}a&&D(a),g.onUpdate.listen((()=>{f.isRunning()&&h.retranslate()}));const F=Object.freeze(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},g),f),h),m),{init:D,getTranslation:A,changeTranslation:N,getTranslationNs:I,getDefaultAndFallbackNs:w,async changeLanguage(e){f.getPendingLanguage()===e&&f.getLanguage()===e||(f.setPendingLanguage(e),f.isRunning()&&await C(e),e===f.getPendingLanguage()&&(f.setLanguage(e),h.setStoredLanguage(e)))},async addActiveNs(e,n){n||f.addActiveNs(e),f.isRunning()&&await C(void 0,e)},loadRecords:e=>m.loadRecords(e,F.isDev()),loadRecord:async e=>(await F.loadRecords([e]))[0],isLoading:e=>m.isLoading(f.getLanguage(),e),isLoaded(e){const n=f.getLanguage();if(!n)return!1;const t=f.getFallbackLangs(n),a=E(e),i=[];return t.forEach((e=>{a.forEach((n=>{m.exists({language:e,namespace:n})||i.push({language:e,namespace:n})}))})),0===i.length},t:(...e)=>{const n=k(...e),t=A(n);return h.formatTranslation(Object.assign(Object.assign({},n),{translation:t}))},isDev:()=>Boolean(f.getInitialOptions().apiKey&&f.getInitialOptions().apiUrl),run:()=>(function(){if((h.getLanguageDetector()||h.getLanguageStorage())&&!f.getAvailableLanguages())throw new Error(t("availableLanguages"));if(!f.getLanguage()&&!f.getInitialOptions().defaultLanguage)throw new Error(t(["defaultLanguage","language"]))}(),f.isRunning()||(f.setRunning(!0),h.run(),b=S()),Promise.resolve(b)),stop(){f.isRunning()&&(h.stop(),f.setRunning(!1))}}));return F}const w=()=>{const e={plugins:[],options:{}},n=Object.freeze({use:t=>(e.plugins.push(t),n),updateDefaults:t=>(e.options=O(e.options,t),n),init(n){const t=function(e){const n=R({options:e});function t(e){const t=n.isRunning();t&&n.stop(),e(),n.isDev()&&n.invalidate(),t&&n.run()}n.isDev()&&n.invalidate();const a=Object.freeze({on:n.on,onNsUpdate:n.onUpdate.listenSome,setEmitterActive:n.setEmitterActive,getLanguage:n.getLanguage,getPendingLanguage:n.getPendingLanguage,changeLanguage:n.changeLanguage,changeTranslation:n.changeTranslation,addActiveNs:n.addActiveNs,removeActiveNs:n.removeActiveNs,loadRecords:n.loadRecords,loadRecord:n.loadRecord,addStaticData:n.addStaticData,getRecord:n.getRecord,getAllRecords:n.getAllRecords,isLoaded:n.isLoaded,isInitialLoading:n.isInitialLoading,isLoading:n.isLoading,isFetching:n.isFetching,isRunning:n.isRunning,run:n.run,stop:n.stop,t:n.t,highlight:n.highlight,getInitialOptions:n.getInitialOptions,isDev:n.isDev,wrap:n.wrap,unwrap:n.unwrap,overrideCredentials(e){t((()=>n.overrideCredentials(e)))},addPlugin(e){e&&t((()=>n.addPlugin(a,e)))},updateOptions(e){e&&t((()=>n.init(e)))}});return a}(O(e.options,n));return e.plugins.forEach(t.addPlugin),t}});return n},E=0,N=1,D=2;class C extends Error{constructor(e,n,t){let a;a=e===E?"Empty parameter":e===N?"Unexpected character":"Unexpected end",super(`Tolgee parser: ${a} at ${n} in "${t}"`),this.code=e,this.index=n}}function I(e){return/\s/.test(e)}const A=0,S=1,F=2,P=3,T=4,U=new Set([F,S,A]),B="'",x=new Set(["{","}",B]),z=e=>/[0-9a-zA-Z_]/.test(e);function K(e,n){const[t,a]=function(e){let n=A,t="",a="",i="";const o=[],s=[];let r=0;function g(n){throw new C(n,r,e)}const c=()=>{o.push(t),t=""},l=()=>{""===a&&g(E),s.push(a),a=""};for(r=0;r<e.length;r++)switch(i=e[r],n){case A:i===B?(t+=i,n=S):"{"===i?(c(),n=P):(t+=i,n=A);break;case S:x.has(i)?(t=t.slice(0,-1)+i,n=F):(t+=i,n=A);break;case F:i===B?n=A:(t+=i,n=F);break;case P:"}"===i?(l(),n=A):I(i)?""!==a&&(l(),n=T):(z(i)||g(N),a+=i,n=P);break;case T:"}"==i?n=A:I(i)?n=T:g(N)}return U.has(n)||g(D),c(),[o,s]}(e),i=[t[0]];for(let o=1;o<t.length;o++){const s=null==n?void 0:n[a[o-1]];if(void 0===s)throw new Error(`Missing parameter "${a[o-1]}" in "${e}"`);i.push(String(s)),i.push(t[o])}return i.join("")}const $=()=>(e,n)=>(n.setFinalFormatter({format:({translation:e,params:n})=>K(e,n)}),e);export{$ as FormatSimple,w as TolgeeCore,c as createFetchFunction,a as getFallback,i as getFallbackArray,k as getTranslateProps}; | ||
function e(e){return Boolean(e&&"function"==typeof e.then)}function n(n,t){return e(n)?Promise.resolve(n).then(t):t(n)}function t(n,t,a){function i(e){const a=t(e);throw n.emit(a),console.error(a),a}try{const n=a();return e(n)?n.catch(i):n}catch(e){i(e)}}function a(e){const n=(Array.isArray(e)?e:[e]).map((e=>`'${e}'`)),t=n.slice(-2).join(" or ");return`Tolgee: You need to specify ${[...n.slice(0,-2),t].join(", ")} option`}function i(e){return"string"==typeof e?[e]:Array.isArray(e)?e:void 0}function o(e){return i(e)||[]}function r(e,n){return"object"!=typeof(t=n)||Array.isArray(t)||null===t?o(n):o(null==n?void 0:n[e]);var t}function s(e){return Array.from(new Set(e))}function g(e){return e?e.replace(/\/+$/,""):e}const c=(e,n)=>fetch(e,n),l=(e=c)=>(n,t)=>e(n,Object.assign(Object.assign({},t),{headers:Object.assign({"X-Tolgee-SDK-Type":"JS","X-Tolgee-SDK-Version":process.env.TOLGEE_UI_VERSION||"prerelease"},null==t?void 0:t.headers)}));function u(e){let n=[];return Object.freeze({listen(e){const t=n=>{e(n)};return n.push(t),{unsubscribe(){n=n.filter((e=>t!==e))}}},emit(t){e()&&n.forEach((e=>e({value:t})))}})}function d(e,n,t){const a=new Set,i=new Set;let r=[];function s(){if(0===r.length)return;const e=r;r=[],a.forEach((e=>{e({value:void 0})}));let t=new Set;e.forEach((e=>{void 0===e?t=void 0:void 0!==t&&e.forEach((e=>t.add(e)))}));!function(e){const t=new Set(n());i.forEach((n=>{(void 0===e||-1!==(null==e?void 0:e.findIndex((e=>t.has(e)||n.namespaces.has(e)))))&&n.fn({value:void 0})}))}(t?Array.from(t.keys()):void 0)}return Object.freeze({emit(n,t){e()&&(r.push(n),t?setTimeout(s,0):s())},listen(e){a.add(e);return{unsubscribe:()=>{a.delete(e)}}},listenSome(e){const n={fn:n=>{e(n)},namespaces:new Set};i.add(n);const a={unsubscribe:()=>{i.delete(n)},subscribeNs:e=>(o(e).forEach((e=>n.namespaces.add(e))),void 0===e&&n.namespaces.add(t()),a)};return a}})}class p extends Error{constructor(e,n,t=!1){const{language:a,namespace:i}=e;super(`Tolgee: Failed to fetch record for "${a}"${i&&` and "${i}"`}`),this.cause=n,this.isDev=t,this.name="RecordFetchError",this.language=a,this.namespace=i}}class f extends Error{constructor(e,n){super(e),this.cause=n,this.name="LanguageDetectorError"}}class v extends Error{constructor(e,n){super(e),this.cause=n,this.name="LanguageStorageError"}}const h=e=>{const n=new Map;return Object.entries(e).forEach((([e,t])=>{null!=t&&("object"!=typeof t?n.set(e,t):h(t).forEach(((t,a)=>{n.set(e+"."+a,t)})))})),n},m=e=>{const[n,...t]=e.split(":");return{language:n,namespace:t.join(":")||""}},b=({language:e,namespace:n})=>n?`${e}:${n}`:e;function O(n,t,a,i,r,g,c){const l=new Map,u=new Map;let d={},f=0;function v(e,t,a){const i=b(e);u.set(i,{data:h(t),version:a}),n.onCacheChange.emit(e)}function O(a){let i;if(!i){const e=d[b(a)];"function"==typeof e&&(i=e())}return i||(i=t(a)),e(i)?null==i?void 0:i.catch((e=>{const t=new p(a,e);throw n.onError.emit(t),console.error(t),t})):i}const L=Object.freeze({addStaticData(e){e&&(d=Object.assign(Object.assign({},d),e),Object.entries(e).forEach((([e,n])=>{if("function"!=typeof n){const t=m(e),a=u.get(e);a&&0!==a.version||v(t,n,0)}})))},invalidate(){l.clear(),f+=1},addRecord(e,n){v(e,n,f)},exists(e,n=!1){const t=u.get(b(e));return t&&n?t.version===f:Boolean(t)},getRecord(e){var n;return null===(n=u.get(b(i(e))))||void 0===n?void 0:n.data},getTranslation(e,n){var t;return null===(t=u.get(b(e)))||void 0===t?void 0:t.data.get(n)},getTranslationNs(e,n,t){var a;for(const i of e)for(const e of n){const n=null===(a=u.get(b({language:e,namespace:i})))||void 0===a?void 0:a.data.get(t);if(null!=n)return[i]}return s(e)},getTranslationFallback(e,n,t){var a;for(const i of e)for(const e of n){const n=null===(a=u.get(b({language:e,namespace:i})))||void 0===a?void 0:a.data.get(t);if(null!=n)return n}},changeTranslation(e,t,a){var i;const o=null===(i=u.get(b(e)))||void 0===i?void 0:i.data;null==o||o.set(t,a),n.onCacheChange.emit(Object.assign(Object.assign({},e),{key:t}))},isFetching(e){if(r())return!0;if(void 0===e)return l.size>0;const n=o(e);return Boolean(Array.from(l.keys()).find((e=>n.includes(m(e).namespace))))},isLoading(e,n){const t=o(n);return Boolean(r()||Array.from(l.keys()).find((n=>{const a=m(n);return(!t.length||t.includes(a.namespace))&&!L.exists({namespace:a.namespace,language:e})})))},async loadRecords(e,t){const o=e.map((e=>{const o=i(e),r=b(o),s=l.get(r);if(s)return{new:!1,promise:s,keyObject:o,cacheKey:r};const g=function(e,t){var i;let o;return t&&(o=null===(i=a(e))||void 0===i?void 0:i.catch((t=>{const a=new p(e,t,!0);return n.onError.emit(a),console.warn(a),O(e)}))),o||(o=O(e)),o}(o,t)||Promise.resolve(void 0);return l.set(r,g),{new:!0,promise:g,keyObject:o,cacheKey:r}}));g.notify(),c.notify();const r=await Promise.all(o.map((e=>e.promise)));return o.forEach(((e,n)=>{const t=l.get(e.cacheKey)!==e.promise;if(e.new&&!t){l.delete(e.cacheKey);const t=r[n];t?L.addRecord(e.keyObject,t):L.getRecord(e.keyObject)||L.addRecord(e.keyObject,{})}})),g.notify(),c.notify(),o.map((e=>L.getRecord(e.keyObject)))},getAllRecords:()=>Array.from(u.entries()).map((([e,n])=>Object.assign(Object.assign({},m(e)),{data:n.data})))});return L}function L(e,n){var t={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&n.indexOf(a)<0&&(t[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(a=Object.getOwnPropertySymbols(e);i<a.length;i++)n.indexOf(a[i])<0&&Object.prototype.propertyIsEnumerable.call(e,a[i])&&(t[a[i]]=e[a[i]])}return t}const y="invalid",j={defaultNs:"",observerOptions:{tagAttributes:{textarea:["placeholder"],input:["value","placeholder"],img:["alt"],"*":["aria-label","title"]},restrictedElements:["script","style"],highlightKeys:["Alt"],highlightColor:"rgb(255, 0, 0)",highlightWidth:5,inputPrefix:"%-%tolgee:",inputSuffix:"%-%",passToParent:["option","optgroup"],fullKeyEncode:!1},observerType:"invisible",onFormatError:y,apiUrl:"https://app.tolgee.io",fetch:l(),onTranslationMissing:({key:e})=>e},k=(...e)=>{let n={};return e.forEach((e=>{n=Object.assign(Object.assign(Object.assign({},n),e),{observerOptions:Object.assign(Object.assign({},n.observerOptions),null==e?void 0:e.observerOptions)})})),n};function E(e,n){const t=k(j,null==n?void 0:n.initialOptions,e);return t.apiUrl=g(t.apiUrl),(null==e?void 0:e.fetch)&&(t.fetch=l(e.fetch)),{initialOptions:t,activeNamespaces:(null==n?void 0:n.activeNamespaces)||new Map,language:null==n?void 0:n.language,pendingLanguage:null==n?void 0:n.language,isInitialLoading:!1,isRunning:!1}}function w(e,a,i,o,r,s,g,c){const l={ui:void 0},u={formatters:[],finalFormatter:void 0,observer:void 0,devBackend:void 0,backends:[],ui:void 0,languageDetector:void 0,languageStorage:void 0},d=async({keysAndDefaults:e,event:n})=>{var t;const a=e.map((({key:e,ns:n,defaultValue:t})=>({key:e,defaultValue:t,fallbackNamespaces:o(n),namespace:r({key:e,ns:n})[0],translation:s({key:e,ns:n})})));null===(t=u.ui)||void 0===t||t.handleElementClick(a,n)},p=(e,n)=>{var t;return(null===(t=u.observer)||void 0===t?void 0:t.findPositions(e,n))||[]};function h(e){const n=s({key:e.key,ns:e.ns});return I.formatTranslation(Object.assign(Object.assign({},e),{translation:n,formatEnabled:!0}))}function m(){return{fetch:a().fetch}}function b(e){u.observer=null==e?void 0:e()}function O(){return Boolean(u.observer)}function j(e){e&&u.formatters.push(e)}function k(e){u.finalFormatter=e}function E(e){l.ui=e}function w(){return Boolean(l.ui)}function R(e){u.languageStorage=e}function N(e){u.languageDetector=e}function D(e){e&&u.backends.push(e)}function C(e){u.devBackend=e}const I=Object.freeze({addPlugin:function(e,n){n(e,Object.freeze({setFinalFormatter:k,addFormatter:j,setObserver:b,hasObserver:O,setUi:E,hasUi:w,setDevBackend:C,addBackend:D,setLanguageDetector:N,setLanguageStorage:R}))},run(){var e,n;const{apiKey:t,apiUrl:i,projectId:o,observerOptions:r}=a();u.ui=null===(e=l.ui)||void 0===e?void 0:e.call(l,{apiKey:t,apiUrl:i,projectId:o,highlight:I.highlight,changeTranslation:g,findPositions:p,onPermanentChange:e=>c.onPermanentChange.emit(e)}),null===(n=u.observer)||void 0===n||n.run({mouseHighlight:!0,options:r,translate:h,onClick:d})},stop(){var e;u.ui=void 0,null===(e=u.observer)||void 0===e||e.stop()},getLanguageStorage:()=>u.languageStorage,getInitialLanguage(){const e=i();return n(t(c.onError,(e=>new v("Tolgee: Failed to load language",e)),(()=>{var e;return null===(e=u.languageStorage)||void 0===e?void 0:e.getLanguage(m())})),(n=>e&&!e.includes(n)||!n?function(){if(!u.languageDetector)return;const e=i();return t(c.onError,(e=>new f("Tolgee: Failed to detect language",e)),(()=>{var n;return null===(n=u.languageDetector)||void 0===n?void 0:n.getLanguage(Object.assign({availableLanguages:e},m()))}))}():n))},setStoredLanguage:e=>t(c.onError,(e=>new v("Tolgee: Failed to store language",e)),(()=>{var n;return null===(n=u.languageStorage)||void 0===n?void 0:n.setLanguage(e,m())})),getDevBackend:()=>u.devBackend,getBackendRecord:({language:e,namespace:n})=>{for(const t of u.backends){const a=t.getRecord(Object.assign({language:e,namespace:n},m()));if(void 0!==a)return a}},getBackendDevRecord:({language:e,namespace:n})=>{var t;const{apiKey:i,apiUrl:o,projectId:r}=a();return null===(t=u.devBackend)||void 0===t?void 0:t.getRecord(Object.assign({apiKey:i,apiUrl:o,projectId:r,language:e,namespace:n},m()))},getLanguageDetector:()=>u.languageDetector,retranslate(){var e;null===(e=u.observer)||void 0===e||e.retranslate()},highlight:(e,n)=>{var t,a;return(null===(a=null===(t=u.observer)||void 0===t?void 0:t.highlight)||void 0===a?void 0:a.call(t,e,n))||{unhighlight(){}}},unwrap(e){var n;return u.observer?null===(n=u.observer)||void 0===n?void 0:n.unwrap(e):{text:e,keys:[]}},wrap(e){var n;return u.observer?null===(n=u.observer)||void 0===n?void 0:n.wrap(e):e.translation},hasDevBackend:()=>Boolean(I.getDevBackend()),formatTranslation(n){var t,{formatEnabled:i}=n,o=L(n,["formatEnabled"]);const{key:r,translation:s,defaultValue:g,noWrap:c,params:l,ns:d,orEmpty:p}=o,f=null!=s?s:g;let v="";null==s&&(v=a().onTranslationMissing(o));let h=null!=f?f:p?"":v;const m=e(),b=i||!(null===(t=u.observer)||void 0===t?void 0:t.outputNotFormattable),O=e=>u.observer&&!c?u.observer.wrap({key:r,translation:e,defaultValue:g,params:l,ns:d}):e;h=O(h);try{if(f&&m&&b)for(const e of u.formatters)h=e.format({translation:h,language:m,params:l});u.finalFormatter&&f&&m&&b&&(h=u.finalFormatter.format({translation:h,language:m,params:l}))}catch(e){console.error(e);const n=("string"==typeof(j=e)?j:"string"==typeof(null==j?void 0:j.message)?j.message:void 0)||y,t=a().onFormatError,i=typeof t;h="string"===i?t:"function"===i?t(n,o):y,h=O(h)}var j;return h}});return I}const R=(e,n,t)=>{let a=e;return Object.freeze({init(e){a=e},notify(){const e=n();a!==e&&t(e),a=e}})};const N=(e,...n)=>{let t,a={};return"object"==typeof e?a=e:(a.key=e,"string"==typeof n[0]?(a.defaultValue=n[0],t=n[1]):"object"==typeof n[0]&&(t=n[0])),t&&(a=Object.assign(Object.assign({},function(e){var{ns:n,noWrap:t,orEmpty:a,params:i,language:o}=e,r=L(e,["ns","noWrap","orEmpty","params","language"]);const s={ns:n,noWrap:t,orEmpty:a,language:o};return Object.assign(Object.assign({},s),{params:Object.assign({},r)})}(t)),a)),a};function D({options:t}){const i=function(e,n){let t=!0;function a(){return t}const i=Object.freeze({onPendingLanguageChange:u(a),onLanguageChange:u(a),onLoadingChange:u(a),onFetchingChange:u(a),onInitialLoaded:u(a),onRunningChange:u(a),onCacheChange:u(a),onUpdate:d(a,e,n),onPermanentChange:u(a),onError:u(a),setEmitterActive(e){t=e},on:(e,n)=>{switch(e){case"pendingLanguage":return i.onPendingLanguageChange.listen(n);case"language":return i.onLanguageChange.listen(n);case"loading":return i.onLoadingChange.listen(n);case"fetching":return i.onFetchingChange.listen(n);case"initialLoad":return i.onInitialLoaded.listen(n);case"running":return i.onRunningChange.listen(n);case"cache":return i.onCacheChange.listen(n);case"update":return i.onUpdate.listen(n);case"permanentChange":return i.onPermanentChange.listen(n);case"error":return i.onError.listen(n)}}});return i.onInitialLoaded.listen((()=>i.onUpdate.emit())),i.onLanguageChange.listen((()=>i.onUpdate.emit())),i.onCacheChange.listen((({value:e})=>i.onUpdate.emit([e.namespace],!0))),i}(b,L),c=R(!1,(()=>v.isFetching()),i.onFetchingChange.emit),l=R(!1,(()=>S.isLoading()),i.onLoadingChange.emit),p=function(e,n,t){let a,i=E();const c=Object.freeze({init(e){i=E(e,i)},isRunning:()=>i.isRunning,setRunning(e){i.isRunning!==e&&(i.isRunning=e,t.emit(e))},isInitialLoading:()=>i.isInitialLoading,setInitialLoading(e){i.isInitialLoading=e},getLanguage:()=>i.language||i.initialOptions.language,setLanguage(n){i.language!==n&&(i.language=n,e.emit(n))},getPendingLanguage:()=>i.pendingLanguage||c.getLanguage(),setPendingLanguage(e){i.pendingLanguage!==e&&(i.pendingLanguage=e,n.emit(e))},getInitialOptions:()=>Object.assign(Object.assign({},i.initialOptions),a),addActiveNs(e){o(e).forEach((e=>{const n=i.activeNamespaces.get(e);void 0!==n?i.activeNamespaces.set(e,n+1):i.activeNamespaces.set(e,1)}))},removeActiveNs(e){o(e).forEach((e=>{const n=i.activeNamespaces.get(e);void 0!==n&&n>1?i.activeNamespaces.set(e,n-1):i.activeNamespaces.delete(e)}))},getRequiredNamespaces:()=>s([...i.initialOptions.ns||[i.initialOptions.defaultNs],...o(i.initialOptions.fallbackNs),...i.activeNamespaces.keys()]),getFallbackLangs(e){const n=e||c.getLanguage();return n?s([n,...r(n,i.initialOptions.fallbackLanguage)]):[]},getFallbackNs:()=>o(i.initialOptions.fallbackNs),getDefaultNs:e=>void 0===e?i.initialOptions.defaultNs:e,getAvailableLanguages(){if(i.initialOptions.availableLanguages)return i.initialOptions.availableLanguages;if(i.initialOptions.staticData){const e=Object.keys(i.initialOptions.staticData).map((e=>m(e).language));return Array.from(new Set(e))}},withDefaultNs:e=>({namespace:void 0===e.namespace?c.getInitialOptions().defaultNs:e.namespace,language:e.language}),overrideCredentials(e){a=e?Object.assign(Object.assign({},e),{apiUrl:g(e.apiUrl)}):void 0}});return c}(i.onLanguageChange,i.onPendingLanguageChange,i.onRunningChange),f=w(p.getLanguage,p.getInitialOptions,p.getAvailableLanguages,y,I,A,k,i),v=O(i,f.getBackendRecord,f.getBackendDevRecord,p.withDefaultNs,p.isInitialLoading,c,l);let h;function b(){return p.getFallbackNs()}function L(e){return p.getDefaultNs(e)}function y(e){return[...o(L(e)),...b()]}function j(e){return[...o(null!=e?e:L()),...p.getRequiredNamespaces()]}function k(e,n,t){const a=p.withDefaultNs(e),i=v.getTranslation(a,n);return v.changeTranslation(a,n,t),{revert(){v.changeTranslation(a,n,i)}}}function D(e){p.init(e),v.addStaticData(p.getInitialOptions().staticData)}function C(e,t){const a=function(e,n){const t=p.getFallbackLangs(e),a=j(n),i=[];return t.forEach((e=>{a.forEach((n=>{v.exists({language:e,namespace:n},!0)||i.push({language:e,namespace:n})}))})),i}(e,t);if(a.length)return n(S.loadRecords(a),(()=>{}))}function I({key:e,ns:n}){const t=p.getFallbackLangs(),a=y(null!=n?n:void 0);return v.getTranslationNs(a,t,e)}function A({key:e,ns:n,language:t}){const a=y(null!=n?n:void 0),i=p.getFallbackLangs(t);return v.getTranslationFallback(a,i,e)}function F(){const t=n(function(){if(p.getLanguage())return;return n(f.getInitialLanguage(),(e=>{const n=e||p.getInitialOptions().defaultLanguage;n&&p.setLanguage(n)}))}(),(()=>C()));if(e(t))return p.setInitialLoading(!0),c.notify(),l.notify(),Promise.resolve(t).then((()=>{p.setInitialLoading(!1),c.notify(),l.notify(),i.onInitialLoaded.emit()}));i.onInitialLoaded.emit()}t&&D(t),i.onUpdate.listen((()=>{p.isRunning()&&f.retranslate()}));const S=Object.freeze(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},i),p),f),v),{init:D,getTranslation:A,changeTranslation:k,getTranslationNs:I,getDefaultAndFallbackNs:y,async changeLanguage(e){p.getPendingLanguage()===e&&p.getLanguage()===e||(p.setPendingLanguage(e),p.isRunning()&&await C(e),e===p.getPendingLanguage()&&(p.setLanguage(e),await f.setStoredLanguage(e)))},async addActiveNs(e,n){n||p.addActiveNs(e),p.isRunning()&&await C(void 0,e)},loadRecords:e=>v.loadRecords(e,S.isDev()),loadRecord:async e=>(await S.loadRecords([e]))[0],isLoading:e=>v.isLoading(p.getLanguage(),e),isLoaded(e){const n=p.getLanguage();if(!n)return!1;const t=p.getFallbackLangs(n),a=j(e),i=[];return t.forEach((e=>{a.forEach((n=>{v.exists({language:e,namespace:n})||i.push({language:e,namespace:n})}))})),0===i.length},t:(...e)=>{const n=N(...e),t=A(n);return f.formatTranslation(Object.assign(Object.assign({},n),{translation:t}))},isDev:()=>Boolean(p.getInitialOptions().apiKey&&p.getInitialOptions().apiUrl),run:()=>(function(){if((f.getLanguageDetector()||f.getLanguageStorage())&&!p.getAvailableLanguages())throw new Error(a("availableLanguages"));if(!p.getLanguage()&&!p.getInitialOptions().defaultLanguage)throw new Error(a(["defaultLanguage","language"]))}(),p.isRunning()||(p.setRunning(!0),f.run(),h=F()),Promise.resolve(h)),stop(){p.isRunning()&&(f.stop(),p.setRunning(!1))}}));return S}const C=()=>{const e={plugins:[],options:{}},n=Object.freeze({use:t=>(e.plugins.push(t),n),updateDefaults:t=>(e.options=k(e.options,t),n),init(n){const t=function(e){const n=D({options:e});function t(e){const t=n.isRunning();t&&n.stop(),e(),n.isDev()&&n.invalidate(),t&&n.run()}n.isDev()&&n.invalidate();const a=Object.freeze({on:n.on,onNsUpdate:n.onUpdate.listenSome,setEmitterActive:n.setEmitterActive,getLanguage:n.getLanguage,getPendingLanguage:n.getPendingLanguage,changeLanguage:n.changeLanguage,changeTranslation:n.changeTranslation,addActiveNs:n.addActiveNs,removeActiveNs:n.removeActiveNs,loadRecords:n.loadRecords,loadRecord:n.loadRecord,addStaticData:n.addStaticData,getRecord:n.getRecord,getAllRecords:n.getAllRecords,isLoaded:n.isLoaded,isInitialLoading:n.isInitialLoading,isLoading:n.isLoading,isFetching:n.isFetching,isRunning:n.isRunning,run:n.run,stop:n.stop,t:n.t,highlight:n.highlight,getInitialOptions:n.getInitialOptions,isDev:n.isDev,wrap:n.wrap,unwrap:n.unwrap,overrideCredentials(e){t((()=>n.overrideCredentials(e)))},addPlugin(e){e&&t((()=>n.addPlugin(a,e)))},updateOptions(e){e&&t((()=>n.init(e)))}});return a}(k(e.options,n));return e.plugins.forEach(t.addPlugin),t}});return n},I=0,A=1,F=2;class S extends Error{constructor(e,n,t){let a;a=e===I?"Empty parameter":e===A?"Unexpected character":"Unexpected end",super(`Tolgee parser: ${a} at ${n} in "${t}"`),this.code=e,this.index=n}}function T(e){return/\s/.test(e)}const P=0,U=1,B=2,x=3,z=4,K=new Set([B,U,P]),$="'",M=new Set(["{","}",$]),V=e=>/[0-9a-zA-Z_]/.test(e);function W(e,n){const[t,a]=function(e){let n=P,t="",a="",i="";const o=[],r=[];let s=0;function g(n){throw new S(n,s,e)}const c=()=>{o.push(t),t=""},l=()=>{""===a&&g(I),r.push(a),a=""};for(s=0;s<e.length;s++)switch(i=e[s],n){case P:i===$?(t+=i,n=U):"{"===i?(c(),n=x):(t+=i,n=P);break;case U:M.has(i)?(t=t.slice(0,-1)+i,n=B):(t+=i,n=P);break;case B:i===$?n=P:(t+=i,n=B);break;case x:"}"===i?(l(),n=P):T(i)?""!==a&&(l(),n=z):(V(i)||g(A),a+=i,n=x);break;case z:"}"==i?n=P:T(i)?n=z:g(A)}return K.has(n)||g(F),c(),[o,r]}(e),i=[t[0]];for(let o=1;o<t.length;o++){const r=null==n?void 0:n[a[o-1]];if(void 0===r)throw new Error(`Missing parameter "${a[o-1]}" in "${e}"`);i.push(String(r)),i.push(t[o])}return i.join("")}const _=()=>(e,n)=>(n.setFinalFormatter({format:({translation:e,params:n})=>W(e,n)}),e);export{_ as FormatSimple,f as LanguageDetectorError,v as LanguageStorageError,p as RecordFetchError,C as TolgeeCore,l as createFetchFunction,i as getFallback,o as getFallbackArray,N as getTranslateProps}; | ||
//# sourceMappingURL=tolgee.esm.min.js.map |
@@ -1,2 +0,2 @@ | ||
!function(e,n){"object"==typeof exports&&"undefined"!=typeof module?n(exports):"function"==typeof define&&define.amd?define(["exports"],n):n((e="undefined"!=typeof globalThis?globalThis:e||self)["@tolgee/core"]={})}(this,(function(e){"use strict";function n(e){return Boolean(e&&"function"==typeof e.then)}function t(e,t){return n(e)?Promise.resolve(e).then(t):t(e)}function a(e){const n=(Array.isArray(e)?e:[e]).map((e=>`'${e}'`)),t=n.slice(-2).join(" or ");return`Tolgee: You need to specify ${[...n.slice(0,-2),t].join(", ")} option`}function i(e){return"string"==typeof e?[e]:Array.isArray(e)?e:void 0}function o(e){return i(e)||[]}function s(e,n){return"object"!=typeof(t=n)||Array.isArray(t)||null===t?o(n):o(null==n?void 0:n[e]);var t}function r(e){return Array.from(new Set(e))}function g(e){return e?e.replace(/\/+$/,""):e}const c=(e,n)=>fetch(e,n),l=(e=c)=>(n,t)=>e(n,Object.assign(Object.assign({},t),{headers:Object.assign({"X-Tolgee-SDK-Type":"JS","X-Tolgee-SDK-Version":process.env.TOLGEE_UI_VERSION||"prerelease"},null==t?void 0:t.headers)}));function u(e){let n=[];return Object.freeze({listen(e){const t=n=>{e(n)};return n.push(t),{unsubscribe(){n=n.filter((e=>t!==e))}}},emit(t){e()&&n.forEach((e=>e({value:t})))}})}function d(e,n,t){const a=new Set,i=new Set;let s=[];function r(){if(0===s.length)return;const e=s;s=[],a.forEach((e=>{e({value:void 0})}));let t=new Set;e.forEach((e=>{void 0===e?t=void 0:void 0!==t&&e.forEach((e=>t.add(e)))}));!function(e){const t=new Set(n());i.forEach((n=>{(void 0===e||-1!==(null==e?void 0:e.findIndex((e=>t.has(e)||n.namespaces.has(e)))))&&n.fn({value:void 0})}))}(t?Array.from(t.keys()):void 0)}return Object.freeze({emit(n,t){e()&&(s.push(n),t?setTimeout(r,0):r())},listen(e){a.add(e);return{unsubscribe:()=>{a.delete(e)}}},listenSome(e){const n={fn:n=>{e(n)},namespaces:new Set};i.add(n);const a={unsubscribe:()=>{i.delete(n)},subscribeNs:e=>(o(e).forEach((e=>n.namespaces.add(e))),void 0===e&&n.namespaces.add(t()),a)};return a}})}const f=e=>{const n=new Map;return Object.entries(e).forEach((([e,t])=>{null!=t&&("object"!=typeof t?n.set(e,t):f(t).forEach(((t,a)=>{n.set(e+"."+a,t)})))})),n},p=e=>{const[n,...t]=e.split(":");return{language:n,namespace:t.join(":")||""}},v=({language:e,namespace:n})=>n?`${e}:${n}`:e;function h(e,n,t,a,i,s,g){const c=new Map,l=new Map;let u={},d=0;function h(n,t,a){const i=v(n);l.set(i,{data:f(t),version:a}),e.emit(n)}function m(e){let t;if(!t){const n=u[v(e)];"function"==typeof n&&(t=n())}return t||(t=n(e)),t}const b=Object.freeze({addStaticData(e){e&&(u=Object.assign(Object.assign({},u),e),Object.entries(e).forEach((([e,n])=>{if("function"!=typeof n){const t=p(e),a=l.get(e);a&&0!==a.version||h(t,n,0)}})))},invalidate(){c.clear(),d+=1},addRecord(e,n){h(e,n,d)},exists(e,n=!1){const t=l.get(v(e));return t&&n?t.version===d:Boolean(t)},getRecord(e){var n;return null===(n=l.get(v(a(e))))||void 0===n?void 0:n.data},getTranslation(e,n){var t;return null===(t=l.get(v(e)))||void 0===t?void 0:t.data.get(n)},getTranslationNs(e,n,t){var a;for(const i of e)for(const e of n){const n=null===(a=l.get(v({language:e,namespace:i})))||void 0===a?void 0:a.data.get(t);if(null!=n)return[i]}return r(e)},getTranslationFallback(e,n,t){var a;for(const i of e)for(const e of n){const n=null===(a=l.get(v({language:e,namespace:i})))||void 0===a?void 0:a.data.get(t);if(null!=n)return n}},changeTranslation(n,t,a){var i;const o=null===(i=l.get(v(n)))||void 0===i?void 0:i.data;null==o||o.set(t,a),e.emit(Object.assign(Object.assign({},n),{key:t}))},isFetching(e){if(i())return!0;if(void 0===e)return c.size>0;const n=o(e);return Boolean(Array.from(c.keys()).find((e=>n.includes(p(e).namespace))))},isLoading(e,n){const t=o(n);return Boolean(i()||Array.from(c.keys()).find((n=>{const a=p(n);return(!t.length||t.includes(a.namespace))&&!b.exists({namespace:a.namespace,language:e})})))},async loadRecords(e,n){const i=e.map((e=>{const i=a(e),o=v(i),s=c.get(o);if(s)return{new:!1,promise:s,keyObject:i,cacheKey:o};const r=function(e,n){var a;let i;return n&&(i=null===(a=t(e))||void 0===a?void 0:a.catch((()=>(console.warn("Tolgee: Failed to fetch data from dev backend"),m(e))))),i||(i=m(e)),i}(i,n)||Promise.resolve(void 0);return c.set(o,r),{new:!0,promise:r,keyObject:i,cacheKey:o}}));s.notify(),g.notify();const o=await Promise.all(i.map((e=>e.promise)));return i.forEach(((e,n)=>{const t=c.get(e.cacheKey)!==e.promise;if(e.new&&!t){c.delete(e.cacheKey);const t=o[n];t?b.addRecord(e.keyObject,t):b.getRecord(e.keyObject)||b.addRecord(e.keyObject,{})}})),s.notify(),g.notify(),i.map((e=>b.getRecord(e.keyObject)))},getAllRecords:()=>Array.from(l.entries()).map((([e,n])=>Object.assign(Object.assign({},p(e)),{data:n.data})))});return b}function m(e,n){var t={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&n.indexOf(a)<0&&(t[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(a=Object.getOwnPropertySymbols(e);i<a.length;i++)n.indexOf(a[i])<0&&Object.prototype.propertyIsEnumerable.call(e,a[i])&&(t[a[i]]=e[a[i]])}return t}const b="invalid",y={defaultNs:"",observerOptions:{tagAttributes:{textarea:["placeholder"],input:["value","placeholder"],img:["alt"],"*":["aria-label","title"]},restrictedElements:["script","style"],highlightKeys:["Alt"],highlightColor:"rgb(255, 0, 0)",highlightWidth:5,inputPrefix:"%-%tolgee:",inputSuffix:"%-%",passToParent:["option","optgroup"],fullKeyEncode:!1},observerType:"invisible",onFormatError:b,apiUrl:"https://app.tolgee.io",fetch:l(),onTranslationMissing:({key:e})=>e},O=(...e)=>{let n={};return e.forEach((e=>{n=Object.assign(Object.assign(Object.assign({},n),e),{observerOptions:Object.assign(Object.assign({},n.observerOptions),null==e?void 0:e.observerOptions)})})),n};function L(e,n){const t=O(y,null==n?void 0:n.initialOptions,e);return t.apiUrl=g(t.apiUrl),(null==e?void 0:e.fetch)&&(t.fetch=l(e.fetch)),{initialOptions:t,activeNamespaces:(null==n?void 0:n.activeNamespaces)||new Map,language:null==n?void 0:n.language,pendingLanguage:null==n?void 0:n.language,isInitialLoading:!1,isRunning:!1}}function j(e,a,i,o,s,r,g,c){const l={ui:void 0},u={formatters:[],finalFormatter:void 0,observer:void 0,devBackend:void 0,backends:[],ui:void 0,languageDetector:void 0,languageStorage:void 0},d=async({keysAndDefaults:e,event:n})=>{var t;const a=e.map((({key:e,ns:n,defaultValue:t})=>({key:e,defaultValue:t,fallbackNamespaces:o(n),namespace:s({key:e,ns:n})[0],translation:r({key:e,ns:n})})));null===(t=u.ui)||void 0===t||t.handleElementClick(a,n)},f=(e,n)=>{var t;return(null===(t=u.observer)||void 0===t?void 0:t.findPositions(e,n))||[]};function p(e){const n=r({key:e.key,ns:e.ns});return D.formatTranslation(Object.assign(Object.assign({},e),{translation:n,formatEnabled:!0}))}function v(){return{fetch:a().fetch}}function h(e){u.observer=null==e?void 0:e()}function y(){return Boolean(u.observer)}function O(e){e&&u.formatters.push(e)}function L(e){u.finalFormatter=e}function j(e){l.ui=e}function k(){return Boolean(l.ui)}function R(e){u.languageStorage=e}function w(e){u.languageDetector=e}function E(e){e&&u.backends.push(e)}function N(e){u.devBackend=e}const D=Object.freeze({addPlugin:function(e,n){n(e,Object.freeze({setFinalFormatter:L,addFormatter:O,setObserver:h,hasObserver:y,setUi:j,hasUi:k,setDevBackend:N,addBackend:E,setLanguageDetector:w,setLanguageStorage:R}))},run(){var e,n;const{apiKey:t,apiUrl:i,projectId:o,observerOptions:s}=a();u.ui=null===(e=l.ui)||void 0===e?void 0:e.call(l,{apiKey:t,apiUrl:i,projectId:o,highlight:D.highlight,changeTranslation:g,findPositions:f,onPermanentChange:c}),null===(n=u.observer)||void 0===n||n.run({mouseHighlight:!0,options:s,translate:p,onClick:d})},stop(){var e;u.ui=void 0,null===(e=u.observer)||void 0===e||e.stop()},getLanguageStorage:()=>u.languageStorage,getInitialLanguage(){var e;const n=i();return t(null===(e=u.languageStorage)||void 0===e?void 0:e.getLanguage(v()),(e=>n&&!n.includes(e)||!e?function(){if(!u.languageDetector)return;const e=i();return u.languageDetector.getLanguage(Object.assign({availableLanguages:e},v()))}():e))},setStoredLanguage(e){var n;null===(n=u.languageStorage)||void 0===n||n.setLanguage(e,v())},getDevBackend:()=>u.devBackend,getBackendRecord:({language:e,namespace:t})=>{for(const a of u.backends){const i=a.getRecord(Object.assign({language:e,namespace:t},v()));if(n(i))return null==i?void 0:i.catch((e=>(console.error(e),{})));if(void 0!==i)return i}},getBackendDevRecord:({language:e,namespace:n})=>{var t;const{apiKey:i,apiUrl:o,projectId:s}=a();return null===(t=u.devBackend)||void 0===t?void 0:t.getRecord(Object.assign({apiKey:i,apiUrl:o,projectId:s,language:e,namespace:n},v()))},getLanguageDetector:()=>u.languageDetector,retranslate(){var e;null===(e=u.observer)||void 0===e||e.retranslate()},highlight:(e,n)=>{var t,a;return(null===(a=null===(t=u.observer)||void 0===t?void 0:t.highlight)||void 0===a?void 0:a.call(t,e,n))||{unhighlight(){}}},unwrap(e){var n;return u.observer?null===(n=u.observer)||void 0===n?void 0:n.unwrap(e):{text:e,keys:[]}},wrap(e){var n;return u.observer?null===(n=u.observer)||void 0===n?void 0:n.wrap(e):e.translation},hasDevBackend:()=>Boolean(D.getDevBackend()),formatTranslation(n){var t,{formatEnabled:i}=n,o=m(n,["formatEnabled"]);const{key:s,translation:r,defaultValue:g,noWrap:c,params:l,ns:d,orEmpty:f}=o,p=null!=r?r:g;let v="";null==r&&(v=a().onTranslationMissing(o));let h=null!=p?p:f?"":v;const y=e(),O=i||!(null===(t=u.observer)||void 0===t?void 0:t.outputNotFormattable),L=e=>u.observer&&!c?u.observer.wrap({key:s,translation:e,defaultValue:g,params:l,ns:d}):e;h=L(h);try{if(p&&y&&O)for(const e of u.formatters)h=e.format({translation:h,language:y,params:l});u.finalFormatter&&p&&y&&O&&(h=u.finalFormatter.format({translation:h,language:y,params:l}))}catch(e){console.error(e);const n=("string"==typeof(j=e)?j:"string"==typeof(null==j?void 0:j.message)?j.message:void 0)||b,t=a().onFormatError,i=typeof t;h="string"===i?t:"function"===i?t(n,o):b,h=L(h)}var j;return h}});return D}const k=(e,n,t)=>{let a=e;return Object.freeze({init(e){a=e},notify(){const e=n();a!==e&&t(e),a=e}})};const R=(e,...n)=>{let t,a={};return"object"==typeof e?a=e:(a.key=e,"string"==typeof n[0]?(a.defaultValue=n[0],t=n[1]):"object"==typeof n[0]&&(t=n[0])),t&&(a=Object.assign(Object.assign({},function(e){var{ns:n,noWrap:t,orEmpty:a,params:i,language:o}=e,s=m(e,["ns","noWrap","orEmpty","params","language"]);const r={ns:n,noWrap:t,orEmpty:a,language:o};return Object.assign(Object.assign({},r),{params:Object.assign({},s)})}(t)),a)),a};function w({options:e}){const i=function(e,n){let t=!0;function a(){return t}const i=Object.freeze({onPendingLanguageChange:u(a),onLanguageChange:u(a),onLoadingChange:u(a),onFetchingChange:u(a),onInitialLoaded:u(a),onRunningChange:u(a),onCacheChange:u(a),onUpdate:d(a,e,n),onPermanentChange:u(a),setEmitterActive(e){t=e},on:(e,n)=>{switch(e){case"pendingLanguage":return i.onPendingLanguageChange.listen(n);case"language":return i.onLanguageChange.listen(n);case"loading":return i.onLoadingChange.listen(n);case"fetching":return i.onFetchingChange.listen(n);case"initialLoad":return i.onInitialLoaded.listen(n);case"running":return i.onRunningChange.listen(n);case"cache":return i.onCacheChange.listen(n);case"update":return i.onUpdate.listen(n);case"permanentChange":return i.onPermanentChange.listen(n)}}});return i.onInitialLoaded.listen((()=>i.onUpdate.emit())),i.onLanguageChange.listen((()=>i.onUpdate.emit())),i.onCacheChange.listen((({value:e})=>i.onUpdate.emit([e.namespace],!0))),i}(y,O),c=k(!1,(()=>m.isFetching()),i.onFetchingChange.emit),l=k(!1,(()=>S.isLoading()),i.onLoadingChange.emit),f=function(e,n,t){let a,i=L();const c=Object.freeze({init(e){i=L(e,i)},isRunning:()=>i.isRunning,setRunning(e){i.isRunning!==e&&(i.isRunning=e,t.emit(e))},isInitialLoading:()=>i.isInitialLoading,setInitialLoading(e){i.isInitialLoading=e},getLanguage:()=>i.language||i.initialOptions.language,setLanguage(n){i.language!==n&&(i.language=n,e.emit(n))},getPendingLanguage:()=>i.pendingLanguage||c.getLanguage(),setPendingLanguage(e){i.pendingLanguage!==e&&(i.pendingLanguage=e,n.emit(e))},getInitialOptions:()=>Object.assign(Object.assign({},i.initialOptions),a),addActiveNs(e){o(e).forEach((e=>{const n=i.activeNamespaces.get(e);void 0!==n?i.activeNamespaces.set(e,n+1):i.activeNamespaces.set(e,1)}))},removeActiveNs(e){o(e).forEach((e=>{const n=i.activeNamespaces.get(e);void 0!==n&&n>1?i.activeNamespaces.set(e,n-1):i.activeNamespaces.delete(e)}))},getRequiredNamespaces:()=>r([...i.initialOptions.ns||[i.initialOptions.defaultNs],...o(i.initialOptions.fallbackNs),...i.activeNamespaces.keys()]),getFallbackLangs(e){const n=e||c.getLanguage();return n?r([n,...s(n,i.initialOptions.fallbackLanguage)]):[]},getFallbackNs:()=>o(i.initialOptions.fallbackNs),getDefaultNs:e=>void 0===e?i.initialOptions.defaultNs:e,getAvailableLanguages(){if(i.initialOptions.availableLanguages)return i.initialOptions.availableLanguages;if(i.initialOptions.staticData){const e=Object.keys(i.initialOptions.staticData).map((e=>p(e).language));return Array.from(new Set(e))}},withDefaultNs:e=>({namespace:void 0===e.namespace?c.getInitialOptions().defaultNs:e.namespace,language:e.language}),overrideCredentials(e){a=e?Object.assign(Object.assign({},e),{apiUrl:g(e.apiUrl)}):void 0}});return c}(i.onLanguageChange,i.onPendingLanguageChange,i.onRunningChange),v=j(f.getLanguage,f.getInitialOptions,f.getAvailableLanguages,w,A,F,N,(function(e){i.onPermanentChange.emit({key:e.key,namespace:e.namespace})})),m=h(i.onCacheChange,v.getBackendRecord,v.getBackendDevRecord,f.withDefaultNs,f.isInitialLoading,c,l);let b;function y(){return f.getFallbackNs()}function O(e){return f.getDefaultNs(e)}function w(e){return[...o(O(e)),...y()]}function E(e){return[...o(null!=e?e:O()),...f.getRequiredNamespaces()]}function N(e,n,t){const a=f.withDefaultNs(e),i=m.getTranslation(a,n);return m.changeTranslation(a,n,t),{revert(){m.changeTranslation(a,n,i)}}}function D(e){f.init(e),m.addStaticData(f.getInitialOptions().staticData)}function C(e,n){const a=function(e,n){const t=f.getFallbackLangs(e),a=E(n),i=[];return t.forEach((e=>{a.forEach((n=>{m.exists({language:e,namespace:n},!0)||i.push({language:e,namespace:n})}))})),i}(e,n);if(a.length)return t(S.loadRecords(a),(()=>{}))}function A({key:e,ns:n}){const t=f.getFallbackLangs(),a=w(null!=n?n:void 0);return m.getTranslationNs(a,t,e)}function F({key:e,ns:n,language:t}){const a=w(null!=n?n:void 0),i=f.getFallbackLangs(t);return m.getTranslationFallback(a,i,e)}function I(){const e=t(function(){if(f.getLanguage())return;return t(v.getInitialLanguage(),(e=>{const n=e||f.getInitialOptions().defaultLanguage;n&&f.setLanguage(n)}))}(),(()=>C()));if(n(e))return f.setInitialLoading(!0),c.notify(),l.notify(),Promise.resolve(e).then((()=>{f.setInitialLoading(!1),c.notify(),l.notify(),i.onInitialLoaded.emit()}));i.onInitialLoaded.emit()}e&&D(e),i.onUpdate.listen((()=>{f.isRunning()&&v.retranslate()}));const S=Object.freeze(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},i),f),v),m),{init:D,getTranslation:F,changeTranslation:N,getTranslationNs:A,getDefaultAndFallbackNs:w,async changeLanguage(e){f.getPendingLanguage()===e&&f.getLanguage()===e||(f.setPendingLanguage(e),f.isRunning()&&await C(e),e===f.getPendingLanguage()&&(f.setLanguage(e),v.setStoredLanguage(e)))},async addActiveNs(e,n){n||f.addActiveNs(e),f.isRunning()&&await C(void 0,e)},loadRecords:e=>m.loadRecords(e,S.isDev()),loadRecord:async e=>(await S.loadRecords([e]))[0],isLoading:e=>m.isLoading(f.getLanguage(),e),isLoaded(e){const n=f.getLanguage();if(!n)return!1;const t=f.getFallbackLangs(n),a=E(e),i=[];return t.forEach((e=>{a.forEach((n=>{m.exists({language:e,namespace:n})||i.push({language:e,namespace:n})}))})),0===i.length},t:(...e)=>{const n=R(...e),t=F(n);return v.formatTranslation(Object.assign(Object.assign({},n),{translation:t}))},isDev:()=>Boolean(f.getInitialOptions().apiKey&&f.getInitialOptions().apiUrl),run:()=>(function(){if((v.getLanguageDetector()||v.getLanguageStorage())&&!f.getAvailableLanguages())throw new Error(a("availableLanguages"));if(!f.getLanguage()&&!f.getInitialOptions().defaultLanguage)throw new Error(a(["defaultLanguage","language"]))}(),f.isRunning()||(f.setRunning(!0),v.run(),b=I()),Promise.resolve(b)),stop(){f.isRunning()&&(v.stop(),f.setRunning(!1))}}));return S}const E=0,N=1,D=2;class C extends Error{constructor(e,n,t){let a;a=e===E?"Empty parameter":e===N?"Unexpected character":"Unexpected end",super(`Tolgee parser: ${a} at ${n} in "${t}"`),this.code=e,this.index=n}}function A(e){return/\s/.test(e)}const F=0,I=1,S=2,T=3,P=4,U=new Set([S,I,F]),B="'",x=new Set(["{","}",B]),z=e=>/[0-9a-zA-Z_]/.test(e);function K(e,n){const[t,a]=function(e){let n=F,t="",a="",i="";const o=[],s=[];let r=0;function g(n){throw new C(n,r,e)}const c=()=>{o.push(t),t=""},l=()=>{""===a&&g(E),s.push(a),a=""};for(r=0;r<e.length;r++)switch(i=e[r],n){case F:i===B?(t+=i,n=I):"{"===i?(c(),n=T):(t+=i,n=F);break;case I:x.has(i)?(t=t.slice(0,-1)+i,n=S):(t+=i,n=F);break;case S:i===B?n=F:(t+=i,n=S);break;case T:"}"===i?(l(),n=F):A(i)?""!==a&&(l(),n=P):(z(i)||g(N),a+=i,n=T);break;case P:"}"==i?n=F:A(i)?n=P:g(N)}return U.has(n)||g(D),c(),[o,s]}(e),i=[t[0]];for(let o=1;o<t.length;o++){const s=null==n?void 0:n[a[o-1]];if(void 0===s)throw new Error(`Missing parameter "${a[o-1]}" in "${e}"`);i.push(String(s)),i.push(t[o])}return i.join("")}e.FormatSimple=()=>(e,n)=>(n.setFinalFormatter({format:({translation:e,params:n})=>K(e,n)}),e),e.TolgeeCore=()=>{const e={plugins:[],options:{}},n=Object.freeze({use:t=>(e.plugins.push(t),n),updateDefaults:t=>(e.options=O(e.options,t),n),init(n){const t=function(e){const n=w({options:e});function t(e){const t=n.isRunning();t&&n.stop(),e(),n.isDev()&&n.invalidate(),t&&n.run()}n.isDev()&&n.invalidate();const a=Object.freeze({on:n.on,onNsUpdate:n.onUpdate.listenSome,setEmitterActive:n.setEmitterActive,getLanguage:n.getLanguage,getPendingLanguage:n.getPendingLanguage,changeLanguage:n.changeLanguage,changeTranslation:n.changeTranslation,addActiveNs:n.addActiveNs,removeActiveNs:n.removeActiveNs,loadRecords:n.loadRecords,loadRecord:n.loadRecord,addStaticData:n.addStaticData,getRecord:n.getRecord,getAllRecords:n.getAllRecords,isLoaded:n.isLoaded,isInitialLoading:n.isInitialLoading,isLoading:n.isLoading,isFetching:n.isFetching,isRunning:n.isRunning,run:n.run,stop:n.stop,t:n.t,highlight:n.highlight,getInitialOptions:n.getInitialOptions,isDev:n.isDev,wrap:n.wrap,unwrap:n.unwrap,overrideCredentials(e){t((()=>n.overrideCredentials(e)))},addPlugin(e){e&&t((()=>n.addPlugin(a,e)))},updateOptions(e){e&&t((()=>n.init(e)))}});return a}(O(e.options,n));return e.plugins.forEach(t.addPlugin),t}});return n},e.createFetchFunction=l,e.getFallback=i,e.getFallbackArray=o,e.getTranslateProps=R,Object.defineProperty(e,"__esModule",{value:!0})})); | ||
!function(e,n){"object"==typeof exports&&"undefined"!=typeof module?n(exports):"function"==typeof define&&define.amd?define(["exports"],n):n((e="undefined"!=typeof globalThis?globalThis:e||self)["@tolgee/core"]={})}(this,(function(e){"use strict";function n(e){return Boolean(e&&"function"==typeof e.then)}function t(e,t){return n(e)?Promise.resolve(e).then(t):t(e)}function a(e,t,a){function i(n){const a=t(n);throw e.emit(a),console.error(a),a}try{const e=a();return n(e)?e.catch(i):e}catch(e){i(e)}}function i(e){const n=(Array.isArray(e)?e:[e]).map((e=>`'${e}'`)),t=n.slice(-2).join(" or ");return`Tolgee: You need to specify ${[...n.slice(0,-2),t].join(", ")} option`}function o(e){return"string"==typeof e?[e]:Array.isArray(e)?e:void 0}function r(e){return o(e)||[]}function s(e,n){return"object"!=typeof(t=n)||Array.isArray(t)||null===t?r(n):r(null==n?void 0:n[e]);var t}function g(e){return Array.from(new Set(e))}function c(e){return e?e.replace(/\/+$/,""):e}const l=(e,n)=>fetch(e,n),u=(e=l)=>(n,t)=>e(n,Object.assign(Object.assign({},t),{headers:Object.assign({"X-Tolgee-SDK-Type":"JS","X-Tolgee-SDK-Version":process.env.TOLGEE_UI_VERSION||"prerelease"},null==t?void 0:t.headers)}));function d(e){let n=[];return Object.freeze({listen(e){const t=n=>{e(n)};return n.push(t),{unsubscribe(){n=n.filter((e=>t!==e))}}},emit(t){e()&&n.forEach((e=>e({value:t})))}})}function f(e,n,t){const a=new Set,i=new Set;let o=[];function s(){if(0===o.length)return;const e=o;o=[],a.forEach((e=>{e({value:void 0})}));let t=new Set;e.forEach((e=>{void 0===e?t=void 0:void 0!==t&&e.forEach((e=>t.add(e)))}));!function(e){const t=new Set(n());i.forEach((n=>{(void 0===e||-1!==(null==e?void 0:e.findIndex((e=>t.has(e)||n.namespaces.has(e)))))&&n.fn({value:void 0})}))}(t?Array.from(t.keys()):void 0)}return Object.freeze({emit(n,t){e()&&(o.push(n),t?setTimeout(s,0):s())},listen(e){a.add(e);return{unsubscribe:()=>{a.delete(e)}}},listenSome(e){const n={fn:n=>{e(n)},namespaces:new Set};i.add(n);const a={unsubscribe:()=>{i.delete(n)},subscribeNs:e=>(r(e).forEach((e=>n.namespaces.add(e))),void 0===e&&n.namespaces.add(t()),a)};return a}})}class p extends Error{constructor(e,n,t=!1){const{language:a,namespace:i}=e;super(`Tolgee: Failed to fetch record for "${a}"${i&&` and "${i}"`}`),this.cause=n,this.isDev=t,this.name="RecordFetchError",this.language=a,this.namespace=i}}class v extends Error{constructor(e,n){super(e),this.cause=n,this.name="LanguageDetectorError"}}class h extends Error{constructor(e,n){super(e),this.cause=n,this.name="LanguageStorageError"}}const m=e=>{const n=new Map;return Object.entries(e).forEach((([e,t])=>{null!=t&&("object"!=typeof t?n.set(e,t):m(t).forEach(((t,a)=>{n.set(e+"."+a,t)})))})),n},b=e=>{const[n,...t]=e.split(":");return{language:n,namespace:t.join(":")||""}},y=({language:e,namespace:n})=>n?`${e}:${n}`:e;function O(e,t,a,i,o,s,c){const l=new Map,u=new Map;let d={},f=0;function v(n,t,a){const i=y(n);u.set(i,{data:m(t),version:a}),e.onCacheChange.emit(n)}function h(a){let i;if(!i){const e=d[y(a)];"function"==typeof e&&(i=e())}return i||(i=t(a)),n(i)?null==i?void 0:i.catch((n=>{const t=new p(a,n);throw e.onError.emit(t),console.error(t),t})):i}const O=Object.freeze({addStaticData(e){e&&(d=Object.assign(Object.assign({},d),e),Object.entries(e).forEach((([e,n])=>{if("function"!=typeof n){const t=b(e),a=u.get(e);a&&0!==a.version||v(t,n,0)}})))},invalidate(){l.clear(),f+=1},addRecord(e,n){v(e,n,f)},exists(e,n=!1){const t=u.get(y(e));return t&&n?t.version===f:Boolean(t)},getRecord(e){var n;return null===(n=u.get(y(i(e))))||void 0===n?void 0:n.data},getTranslation(e,n){var t;return null===(t=u.get(y(e)))||void 0===t?void 0:t.data.get(n)},getTranslationNs(e,n,t){var a;for(const i of e)for(const e of n){const n=null===(a=u.get(y({language:e,namespace:i})))||void 0===a?void 0:a.data.get(t);if(null!=n)return[i]}return g(e)},getTranslationFallback(e,n,t){var a;for(const i of e)for(const e of n){const n=null===(a=u.get(y({language:e,namespace:i})))||void 0===a?void 0:a.data.get(t);if(null!=n)return n}},changeTranslation(n,t,a){var i;const o=null===(i=u.get(y(n)))||void 0===i?void 0:i.data;null==o||o.set(t,a),e.onCacheChange.emit(Object.assign(Object.assign({},n),{key:t}))},isFetching(e){if(o())return!0;if(void 0===e)return l.size>0;const n=r(e);return Boolean(Array.from(l.keys()).find((e=>n.includes(b(e).namespace))))},isLoading(e,n){const t=r(n);return Boolean(o()||Array.from(l.keys()).find((n=>{const a=b(n);return(!t.length||t.includes(a.namespace))&&!O.exists({namespace:a.namespace,language:e})})))},async loadRecords(n,t){const o=n.map((n=>{const o=i(n),r=y(o),s=l.get(r);if(s)return{new:!1,promise:s,keyObject:o,cacheKey:r};const g=function(n,t){var i;let o;return t&&(o=null===(i=a(n))||void 0===i?void 0:i.catch((t=>{const a=new p(n,t,!0);return e.onError.emit(a),console.warn(a),h(n)}))),o||(o=h(n)),o}(o,t)||Promise.resolve(void 0);return l.set(r,g),{new:!0,promise:g,keyObject:o,cacheKey:r}}));s.notify(),c.notify();const r=await Promise.all(o.map((e=>e.promise)));return o.forEach(((e,n)=>{const t=l.get(e.cacheKey)!==e.promise;if(e.new&&!t){l.delete(e.cacheKey);const t=r[n];t?O.addRecord(e.keyObject,t):O.getRecord(e.keyObject)||O.addRecord(e.keyObject,{})}})),s.notify(),c.notify(),o.map((e=>O.getRecord(e.keyObject)))},getAllRecords:()=>Array.from(u.entries()).map((([e,n])=>Object.assign(Object.assign({},b(e)),{data:n.data})))});return O}function L(e,n){var t={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&n.indexOf(a)<0&&(t[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(a=Object.getOwnPropertySymbols(e);i<a.length;i++)n.indexOf(a[i])<0&&Object.prototype.propertyIsEnumerable.call(e,a[i])&&(t[a[i]]=e[a[i]])}return t}const j="invalid",k={defaultNs:"",observerOptions:{tagAttributes:{textarea:["placeholder"],input:["value","placeholder"],img:["alt"],"*":["aria-label","title"]},restrictedElements:["script","style"],highlightKeys:["Alt"],highlightColor:"rgb(255, 0, 0)",highlightWidth:5,inputPrefix:"%-%tolgee:",inputSuffix:"%-%",passToParent:["option","optgroup"],fullKeyEncode:!1},observerType:"invisible",onFormatError:j,apiUrl:"https://app.tolgee.io",fetch:u(),onTranslationMissing:({key:e})=>e},E=(...e)=>{let n={};return e.forEach((e=>{n=Object.assign(Object.assign(Object.assign({},n),e),{observerOptions:Object.assign(Object.assign({},n.observerOptions),null==e?void 0:e.observerOptions)})})),n};function w(e,n){const t=E(k,null==n?void 0:n.initialOptions,e);return t.apiUrl=c(t.apiUrl),(null==e?void 0:e.fetch)&&(t.fetch=u(e.fetch)),{initialOptions:t,activeNamespaces:(null==n?void 0:n.activeNamespaces)||new Map,language:null==n?void 0:n.language,pendingLanguage:null==n?void 0:n.language,isInitialLoading:!1,isRunning:!1}}function R(e,n,i,o,r,s,g,c){const l={ui:void 0},u={formatters:[],finalFormatter:void 0,observer:void 0,devBackend:void 0,backends:[],ui:void 0,languageDetector:void 0,languageStorage:void 0},d=async({keysAndDefaults:e,event:n})=>{var t;const a=e.map((({key:e,ns:n,defaultValue:t})=>({key:e,defaultValue:t,fallbackNamespaces:o(n),namespace:r({key:e,ns:n})[0],translation:s({key:e,ns:n})})));null===(t=u.ui)||void 0===t||t.handleElementClick(a,n)},f=(e,n)=>{var t;return(null===(t=u.observer)||void 0===t?void 0:t.findPositions(e,n))||[]};function p(e){const n=s({key:e.key,ns:e.ns});return C.formatTranslation(Object.assign(Object.assign({},e),{translation:n,formatEnabled:!0}))}function m(){return{fetch:n().fetch}}function b(e){u.observer=null==e?void 0:e()}function y(){return Boolean(u.observer)}function O(e){e&&u.formatters.push(e)}function k(e){u.finalFormatter=e}function E(e){l.ui=e}function w(){return Boolean(l.ui)}function R(e){u.languageStorage=e}function N(e){u.languageDetector=e}function D(e){e&&u.backends.push(e)}function F(e){u.devBackend=e}const C=Object.freeze({addPlugin:function(e,n){n(e,Object.freeze({setFinalFormatter:k,addFormatter:O,setObserver:b,hasObserver:y,setUi:E,hasUi:w,setDevBackend:F,addBackend:D,setLanguageDetector:N,setLanguageStorage:R}))},run(){var e,t;const{apiKey:a,apiUrl:i,projectId:o,observerOptions:r}=n();u.ui=null===(e=l.ui)||void 0===e?void 0:e.call(l,{apiKey:a,apiUrl:i,projectId:o,highlight:C.highlight,changeTranslation:g,findPositions:f,onPermanentChange:e=>c.onPermanentChange.emit(e)}),null===(t=u.observer)||void 0===t||t.run({mouseHighlight:!0,options:r,translate:p,onClick:d})},stop(){var e;u.ui=void 0,null===(e=u.observer)||void 0===e||e.stop()},getLanguageStorage:()=>u.languageStorage,getInitialLanguage(){const e=i();return t(a(c.onError,(e=>new h("Tolgee: Failed to load language",e)),(()=>{var e;return null===(e=u.languageStorage)||void 0===e?void 0:e.getLanguage(m())})),(n=>e&&!e.includes(n)||!n?function(){if(!u.languageDetector)return;const e=i();return a(c.onError,(e=>new v("Tolgee: Failed to detect language",e)),(()=>{var n;return null===(n=u.languageDetector)||void 0===n?void 0:n.getLanguage(Object.assign({availableLanguages:e},m()))}))}():n))},setStoredLanguage:e=>a(c.onError,(e=>new h("Tolgee: Failed to store language",e)),(()=>{var n;return null===(n=u.languageStorage)||void 0===n?void 0:n.setLanguage(e,m())})),getDevBackend:()=>u.devBackend,getBackendRecord:({language:e,namespace:n})=>{for(const t of u.backends){const a=t.getRecord(Object.assign({language:e,namespace:n},m()));if(void 0!==a)return a}},getBackendDevRecord:({language:e,namespace:t})=>{var a;const{apiKey:i,apiUrl:o,projectId:r}=n();return null===(a=u.devBackend)||void 0===a?void 0:a.getRecord(Object.assign({apiKey:i,apiUrl:o,projectId:r,language:e,namespace:t},m()))},getLanguageDetector:()=>u.languageDetector,retranslate(){var e;null===(e=u.observer)||void 0===e||e.retranslate()},highlight:(e,n)=>{var t,a;return(null===(a=null===(t=u.observer)||void 0===t?void 0:t.highlight)||void 0===a?void 0:a.call(t,e,n))||{unhighlight(){}}},unwrap(e){var n;return u.observer?null===(n=u.observer)||void 0===n?void 0:n.unwrap(e):{text:e,keys:[]}},wrap(e){var n;return u.observer?null===(n=u.observer)||void 0===n?void 0:n.wrap(e):e.translation},hasDevBackend:()=>Boolean(C.getDevBackend()),formatTranslation(t){var a,{formatEnabled:i}=t,o=L(t,["formatEnabled"]);const{key:r,translation:s,defaultValue:g,noWrap:c,params:l,ns:d,orEmpty:f}=o,p=null!=s?s:g;let v="";null==s&&(v=n().onTranslationMissing(o));let h=null!=p?p:f?"":v;const m=e(),b=i||!(null===(a=u.observer)||void 0===a?void 0:a.outputNotFormattable),y=e=>u.observer&&!c?u.observer.wrap({key:r,translation:e,defaultValue:g,params:l,ns:d}):e;h=y(h);try{if(p&&m&&b)for(const e of u.formatters)h=e.format({translation:h,language:m,params:l});u.finalFormatter&&p&&m&&b&&(h=u.finalFormatter.format({translation:h,language:m,params:l}))}catch(e){console.error(e);const t=("string"==typeof(O=e)?O:"string"==typeof(null==O?void 0:O.message)?O.message:void 0)||j,a=n().onFormatError,i=typeof a;h="string"===i?a:"function"===i?a(t,o):j,h=y(h)}var O;return h}});return C}const N=(e,n,t)=>{let a=e;return Object.freeze({init(e){a=e},notify(){const e=n();a!==e&&t(e),a=e}})};const D=(e,...n)=>{let t,a={};return"object"==typeof e?a=e:(a.key=e,"string"==typeof n[0]?(a.defaultValue=n[0],t=n[1]):"object"==typeof n[0]&&(t=n[0])),t&&(a=Object.assign(Object.assign({},function(e){var{ns:n,noWrap:t,orEmpty:a,params:i,language:o}=e,r=L(e,["ns","noWrap","orEmpty","params","language"]);const s={ns:n,noWrap:t,orEmpty:a,language:o};return Object.assign(Object.assign({},s),{params:Object.assign({},r)})}(t)),a)),a};function F({options:e}){const a=function(e,n){let t=!0;function a(){return t}const i=Object.freeze({onPendingLanguageChange:d(a),onLanguageChange:d(a),onLoadingChange:d(a),onFetchingChange:d(a),onInitialLoaded:d(a),onRunningChange:d(a),onCacheChange:d(a),onUpdate:f(a,e,n),onPermanentChange:d(a),onError:d(a),setEmitterActive(e){t=e},on:(e,n)=>{switch(e){case"pendingLanguage":return i.onPendingLanguageChange.listen(n);case"language":return i.onLanguageChange.listen(n);case"loading":return i.onLoadingChange.listen(n);case"fetching":return i.onFetchingChange.listen(n);case"initialLoad":return i.onInitialLoaded.listen(n);case"running":return i.onRunningChange.listen(n);case"cache":return i.onCacheChange.listen(n);case"update":return i.onUpdate.listen(n);case"permanentChange":return i.onPermanentChange.listen(n);case"error":return i.onError.listen(n)}}});return i.onInitialLoaded.listen((()=>i.onUpdate.emit())),i.onLanguageChange.listen((()=>i.onUpdate.emit())),i.onCacheChange.listen((({value:e})=>i.onUpdate.emit([e.namespace],!0))),i}(m,y),o=N(!1,(()=>v.isFetching()),a.onFetchingChange.emit),l=N(!1,(()=>A.isLoading()),a.onLoadingChange.emit),u=function(e,n,t){let a,i=w();const o=Object.freeze({init(e){i=w(e,i)},isRunning:()=>i.isRunning,setRunning(e){i.isRunning!==e&&(i.isRunning=e,t.emit(e))},isInitialLoading:()=>i.isInitialLoading,setInitialLoading(e){i.isInitialLoading=e},getLanguage:()=>i.language||i.initialOptions.language,setLanguage(n){i.language!==n&&(i.language=n,e.emit(n))},getPendingLanguage:()=>i.pendingLanguage||o.getLanguage(),setPendingLanguage(e){i.pendingLanguage!==e&&(i.pendingLanguage=e,n.emit(e))},getInitialOptions:()=>Object.assign(Object.assign({},i.initialOptions),a),addActiveNs(e){r(e).forEach((e=>{const n=i.activeNamespaces.get(e);void 0!==n?i.activeNamespaces.set(e,n+1):i.activeNamespaces.set(e,1)}))},removeActiveNs(e){r(e).forEach((e=>{const n=i.activeNamespaces.get(e);void 0!==n&&n>1?i.activeNamespaces.set(e,n-1):i.activeNamespaces.delete(e)}))},getRequiredNamespaces:()=>g([...i.initialOptions.ns||[i.initialOptions.defaultNs],...r(i.initialOptions.fallbackNs),...i.activeNamespaces.keys()]),getFallbackLangs(e){const n=e||o.getLanguage();return n?g([n,...s(n,i.initialOptions.fallbackLanguage)]):[]},getFallbackNs:()=>r(i.initialOptions.fallbackNs),getDefaultNs:e=>void 0===e?i.initialOptions.defaultNs:e,getAvailableLanguages(){if(i.initialOptions.availableLanguages)return i.initialOptions.availableLanguages;if(i.initialOptions.staticData){const e=Object.keys(i.initialOptions.staticData).map((e=>b(e).language));return Array.from(new Set(e))}},withDefaultNs:e=>({namespace:void 0===e.namespace?o.getInitialOptions().defaultNs:e.namespace,language:e.language}),overrideCredentials(e){a=e?Object.assign(Object.assign({},e),{apiUrl:c(e.apiUrl)}):void 0}});return o}(a.onLanguageChange,a.onPendingLanguageChange,a.onRunningChange),p=R(u.getLanguage,u.getInitialOptions,u.getAvailableLanguages,L,C,T,k,a),v=O(a,p.getBackendRecord,p.getBackendDevRecord,u.withDefaultNs,u.isInitialLoading,o,l);let h;function m(){return u.getFallbackNs()}function y(e){return u.getDefaultNs(e)}function L(e){return[...r(y(e)),...m()]}function j(e){return[...r(null!=e?e:y()),...u.getRequiredNamespaces()]}function k(e,n,t){const a=u.withDefaultNs(e),i=v.getTranslation(a,n);return v.changeTranslation(a,n,t),{revert(){v.changeTranslation(a,n,i)}}}function E(e){u.init(e),v.addStaticData(u.getInitialOptions().staticData)}function F(e,n){const a=function(e,n){const t=u.getFallbackLangs(e),a=j(n),i=[];return t.forEach((e=>{a.forEach((n=>{v.exists({language:e,namespace:n},!0)||i.push({language:e,namespace:n})}))})),i}(e,n);if(a.length)return t(A.loadRecords(a),(()=>{}))}function C({key:e,ns:n}){const t=u.getFallbackLangs(),a=L(null!=n?n:void 0);return v.getTranslationNs(a,t,e)}function T({key:e,ns:n,language:t}){const a=L(null!=n?n:void 0),i=u.getFallbackLangs(t);return v.getTranslationFallback(a,i,e)}function S(){const e=t(function(){if(u.getLanguage())return;return t(p.getInitialLanguage(),(e=>{const n=e||u.getInitialOptions().defaultLanguage;n&&u.setLanguage(n)}))}(),(()=>F()));if(n(e))return u.setInitialLoading(!0),o.notify(),l.notify(),Promise.resolve(e).then((()=>{u.setInitialLoading(!1),o.notify(),l.notify(),a.onInitialLoaded.emit()}));a.onInitialLoaded.emit()}e&&E(e),a.onUpdate.listen((()=>{u.isRunning()&&p.retranslate()}));const A=Object.freeze(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},a),u),p),v),{init:E,getTranslation:T,changeTranslation:k,getTranslationNs:C,getDefaultAndFallbackNs:L,async changeLanguage(e){u.getPendingLanguage()===e&&u.getLanguage()===e||(u.setPendingLanguage(e),u.isRunning()&&await F(e),e===u.getPendingLanguage()&&(u.setLanguage(e),await p.setStoredLanguage(e)))},async addActiveNs(e,n){n||u.addActiveNs(e),u.isRunning()&&await F(void 0,e)},loadRecords:e=>v.loadRecords(e,A.isDev()),loadRecord:async e=>(await A.loadRecords([e]))[0],isLoading:e=>v.isLoading(u.getLanguage(),e),isLoaded(e){const n=u.getLanguage();if(!n)return!1;const t=u.getFallbackLangs(n),a=j(e),i=[];return t.forEach((e=>{a.forEach((n=>{v.exists({language:e,namespace:n})||i.push({language:e,namespace:n})}))})),0===i.length},t:(...e)=>{const n=D(...e),t=T(n);return p.formatTranslation(Object.assign(Object.assign({},n),{translation:t}))},isDev:()=>Boolean(u.getInitialOptions().apiKey&&u.getInitialOptions().apiUrl),run:()=>(function(){if((p.getLanguageDetector()||p.getLanguageStorage())&&!u.getAvailableLanguages())throw new Error(i("availableLanguages"));if(!u.getLanguage()&&!u.getInitialOptions().defaultLanguage)throw new Error(i(["defaultLanguage","language"]))}(),u.isRunning()||(u.setRunning(!0),p.run(),h=S()),Promise.resolve(h)),stop(){u.isRunning()&&(p.stop(),u.setRunning(!1))}}));return A}const C=0,T=1,S=2;class A extends Error{constructor(e,n,t){let a;a=e===C?"Empty parameter":e===T?"Unexpected character":"Unexpected end",super(`Tolgee parser: ${a} at ${n} in "${t}"`),this.code=e,this.index=n}}function I(e){return/\s/.test(e)}const P=0,U=1,x=2,B=3,z=4,K=new Set([x,U,P]),$="'",M=new Set(["{","}",$]),V=e=>/[0-9a-zA-Z_]/.test(e);function W(e,n){const[t,a]=function(e){let n=P,t="",a="",i="";const o=[],r=[];let s=0;function g(n){throw new A(n,s,e)}const c=()=>{o.push(t),t=""},l=()=>{""===a&&g(C),r.push(a),a=""};for(s=0;s<e.length;s++)switch(i=e[s],n){case P:i===$?(t+=i,n=U):"{"===i?(c(),n=B):(t+=i,n=P);break;case U:M.has(i)?(t=t.slice(0,-1)+i,n=x):(t+=i,n=P);break;case x:i===$?n=P:(t+=i,n=x);break;case B:"}"===i?(l(),n=P):I(i)?""!==a&&(l(),n=z):(V(i)||g(T),a+=i,n=B);break;case z:"}"==i?n=P:I(i)?n=z:g(T)}return K.has(n)||g(S),c(),[o,r]}(e),i=[t[0]];for(let o=1;o<t.length;o++){const r=null==n?void 0:n[a[o-1]];if(void 0===r)throw new Error(`Missing parameter "${a[o-1]}" in "${e}"`);i.push(String(r)),i.push(t[o])}return i.join("")}e.FormatSimple=()=>(e,n)=>(n.setFinalFormatter({format:({translation:e,params:n})=>W(e,n)}),e),e.LanguageDetectorError=v,e.LanguageStorageError=h,e.RecordFetchError=p,e.TolgeeCore=()=>{const e={plugins:[],options:{}},n=Object.freeze({use:t=>(e.plugins.push(t),n),updateDefaults:t=>(e.options=E(e.options,t),n),init(n){const t=function(e){const n=F({options:e});function t(e){const t=n.isRunning();t&&n.stop(),e(),n.isDev()&&n.invalidate(),t&&n.run()}n.isDev()&&n.invalidate();const a=Object.freeze({on:n.on,onNsUpdate:n.onUpdate.listenSome,setEmitterActive:n.setEmitterActive,getLanguage:n.getLanguage,getPendingLanguage:n.getPendingLanguage,changeLanguage:n.changeLanguage,changeTranslation:n.changeTranslation,addActiveNs:n.addActiveNs,removeActiveNs:n.removeActiveNs,loadRecords:n.loadRecords,loadRecord:n.loadRecord,addStaticData:n.addStaticData,getRecord:n.getRecord,getAllRecords:n.getAllRecords,isLoaded:n.isLoaded,isInitialLoading:n.isInitialLoading,isLoading:n.isLoading,isFetching:n.isFetching,isRunning:n.isRunning,run:n.run,stop:n.stop,t:n.t,highlight:n.highlight,getInitialOptions:n.getInitialOptions,isDev:n.isDev,wrap:n.wrap,unwrap:n.unwrap,overrideCredentials(e){t((()=>n.overrideCredentials(e)))},addPlugin(e){e&&t((()=>n.addPlugin(a,e)))},updateOptions(e){e&&t((()=>n.init(e)))}});return a}(E(e.options,n));return e.plugins.forEach(t.addPlugin),t}});return n},e.createFetchFunction=u,e.getFallback=o,e.getFallbackArray=r,e.getTranslateProps=D,Object.defineProperty(e,"__esModule",{value:!0})})); | ||
//# sourceMappingURL=tolgee.umd.min.js.map |
@@ -1,6 +0,6 @@ | ||
import { CacheDescriptor, CacheDescriptorInternal, CacheDescriptorWithKey, NsFallback, TranslationsFlat, TranslationValue, TreeTranslationsData, BackendGetRecordInternal } from '../../types'; | ||
import { EventEmitterInstance } from '../Events/EventEmitter'; | ||
import { CacheDescriptor, CacheDescriptorInternal, NsFallback, TranslationsFlat, TranslationValue, TreeTranslationsData, BackendGetRecordInternal } from '../../types'; | ||
import { TolgeeStaticData } from '../State/initState'; | ||
import { ValueObserverInstance } from '../ValueObserver'; | ||
export declare function Cache(onCacheChange: EventEmitterInstance<CacheDescriptorWithKey>, backendGetRecord: BackendGetRecordInternal, backendGetDevRecord: BackendGetRecordInternal, withDefaultNs: (descriptor: CacheDescriptor) => CacheDescriptorInternal, isInitialLoading: () => boolean, fetchingObserver: ValueObserverInstance<boolean>, loadingObserver: ValueObserverInstance<boolean>): Readonly<{ | ||
import { EventsInstance } from '../Events/Events'; | ||
export declare function Cache(events: EventsInstance, backendGetRecord: BackendGetRecordInternal, backendGetDevRecord: BackendGetRecordInternal, withDefaultNs: (descriptor: CacheDescriptor) => CacheDescriptorInternal, isInitialLoading: () => boolean, fetchingObserver: ValueObserverInstance<boolean>, loadingObserver: ValueObserverInstance<boolean>): Readonly<{ | ||
addStaticData(data: TolgeeStaticData | undefined): void; | ||
@@ -7,0 +7,0 @@ invalidate(): void; |
@@ -1,2 +0,2 @@ | ||
import { CacheDescriptor, NsFallback, TolgeeOptions, TFnType, NsType, KeyAndNamespacesInternal, TranslationDescriptor } from '../types'; | ||
import { CacheDescriptor, NsFallback, TolgeeOptions, TFnType, NsType, KeyAndNamespacesInternal } from '../types'; | ||
type StateServiceProps = { | ||
@@ -38,3 +38,3 @@ options?: Partial<TolgeeOptions>; | ||
getInitialLanguage: () => string | Promise<string | undefined> | Promise<string | Promise<string | undefined> | undefined> | undefined; | ||
setStoredLanguage: (language: string) => void; | ||
setStoredLanguage: (language: string) => void | Promise<void | undefined> | undefined; | ||
getDevBackend: () => import("../types").BackendDevMiddleware | undefined; | ||
@@ -100,3 +100,4 @@ getBackendRecord: import("../types").BackendGetRecordInternal; | ||
onUpdate: import("./Events/EventEmitterSelective").EventEmitterSelectiveInstance; | ||
onPermanentChange: import("./Events/EventEmitter").EventEmitterInstance<TranslationDescriptor>; | ||
onPermanentChange: import("./Events/EventEmitter").EventEmitterInstance<import("../types").TranslationDescriptor>; | ||
onError: import("./Events/EventEmitter").EventEmitterInstance<import("../types").TolgeeError>; | ||
setEmitterActive: (active: boolean) => void; | ||
@@ -103,0 +104,0 @@ on: import("../types").TolgeeOn<keyof import("../types").EventType>; |
@@ -1,2 +0,2 @@ | ||
import { CacheDescriptorWithKey, TolgeeOn, TranslationDescriptor } from '../../types'; | ||
import { CacheDescriptorWithKey, TolgeeError, TolgeeOn, TranslationDescriptor } from '../../types'; | ||
export declare function Events(getFallbackNs: () => string[], getDefaultNs: () => string): Readonly<{ | ||
@@ -12,2 +12,3 @@ onPendingLanguageChange: import("./EventEmitter").EventEmitterInstance<string>; | ||
onPermanentChange: import("./EventEmitter").EventEmitterInstance<TranslationDescriptor>; | ||
onError: import("./EventEmitter").EventEmitterInstance<TolgeeError>; | ||
setEmitterActive(active: boolean): void; | ||
@@ -14,0 +15,0 @@ on: TolgeeOn<keyof import("../../types").EventType>; |
@@ -1,3 +0,4 @@ | ||
import { BackendDevMiddleware, TranslatePropsInternal, HighlightInterface, LanguageDetectorMiddleware, LanguageStorageMiddleware, ChangeTranslationInterface, WrapperWrapProps, Unwrapped, KeyAndNamespacesInternal, TolgeePlugin, TolgeeInstance, TolgeeOptionsInternal, BackendGetRecordInternal, TranslationDescriptor } from '../../types'; | ||
export declare function Plugins(getLanguage: () => string | undefined, getInitialOptions: () => TolgeeOptionsInternal, getAvailableLanguages: () => string[] | undefined, getFallbackNamespaces: (ns: string | undefined) => string[], getTranslationNs: (props: KeyAndNamespacesInternal) => string[], getTranslation: (props: KeyAndNamespacesInternal) => string | undefined, changeTranslation: ChangeTranslationInterface, onPermanentChange: (props: TranslationDescriptor) => void): Readonly<{ | ||
import { BackendDevMiddleware, TranslatePropsInternal, HighlightInterface, LanguageDetectorMiddleware, LanguageStorageMiddleware, ChangeTranslationInterface, WrapperWrapProps, Unwrapped, KeyAndNamespacesInternal, TolgeePlugin, TolgeeInstance, TolgeeOptionsInternal, BackendGetRecordInternal } from '../../types'; | ||
import { EventsInstance } from '../Events/Events'; | ||
export declare function Plugins(getLanguage: () => string | undefined, getInitialOptions: () => TolgeeOptionsInternal, getAvailableLanguages: () => string[] | undefined, getFallbackNamespaces: (ns: string | undefined) => string[], getTranslationNs: (props: KeyAndNamespacesInternal) => string[], getTranslation: (props: KeyAndNamespacesInternal) => string | undefined, changeTranslation: ChangeTranslationInterface, events: EventsInstance): Readonly<{ | ||
addPlugin: (tolgeeInstance: TolgeeInstance, plugin: TolgeePlugin) => void; | ||
@@ -8,3 +9,3 @@ run(): void; | ||
getInitialLanguage(): string | Promise<string | undefined> | Promise<string | Promise<string | undefined> | undefined> | undefined; | ||
setStoredLanguage(language: string): void; | ||
setStoredLanguage(language: string): void | Promise<void | undefined> | undefined; | ||
getDevBackend(): BackendDevMiddleware | undefined; | ||
@@ -11,0 +12,0 @@ getBackendRecord: BackendGetRecordInternal; |
@@ -1,4 +0,6 @@ | ||
import { FallbackGeneral, FallbackLanguageOption, FetchFn } from './types'; | ||
export declare function isPromise(value: any): boolean; | ||
import { FallbackGeneral, FallbackLanguageOption, FetchFn, TolgeeError } from './types'; | ||
import { EventEmitterInstance } from './Controller/Events/EventEmitter'; | ||
export declare function isPromise(value: unknown): value is Promise<unknown>; | ||
export declare function valueOrPromise<T, R>(value: T | Promise<T>, callback: (value: T) => R): R | Promise<R>; | ||
export declare function handleRegularOrAsyncErr<T>(onError: EventEmitterInstance<TolgeeError>, createError: (e: any) => TolgeeError, callback: () => Promise<T> | T): Promise<T> | T; | ||
export declare function missingOptionError(option: string | string[]): string; | ||
@@ -5,0 +7,0 @@ export declare function isObject(item: any): boolean; |
import type { NsFallback } from './general'; | ||
import type { CacheDescriptorWithKey } from './cache'; | ||
import { TolgeeError } from './errors'; | ||
export type Subscription = { | ||
@@ -30,2 +31,3 @@ unsubscribe: () => void; | ||
update: void; | ||
error: TolgeeError; | ||
permanentChange: CacheDescriptorWithKey; | ||
@@ -68,2 +70,6 @@ } | ||
/** | ||
* Emitted on errors | ||
*/ | ||
(event: 'error', handler: Listener<TolgeeError>): Subscription; | ||
/** | ||
* Translation was changed or created via dev tools | ||
@@ -70,0 +76,0 @@ */ |
@@ -5,4 +5,5 @@ export * from './general'; | ||
export * from './plugin'; | ||
export * from './errors'; | ||
export type { State, TolgeeOptions, TolgeeOptionsInternal, TolgeeStaticData, } from '../Controller/State/initState'; | ||
export type { ObserverOptions, ObserverOptionsInternal, ModifierKey, } from '../Controller/State/observerOptions'; | ||
export type { TolgeeChainer, TolgeeInstance } from '../TolgeeCore'; |
{ | ||
"name": "@tolgee/core", | ||
"version": "5.20.3", | ||
"version": "5.20.4-prerelease.afe383ff.0", | ||
"description": "Library providing ability to translate messages directly in context of developed application.", | ||
@@ -72,3 +72,3 @@ "main": "./dist/tolgee.cjs.js", | ||
"sideEffects": false, | ||
"gitHead": "457db47891e93a6d431cfc76c737f9fe79f81813" | ||
"gitHead": "734f14fd517ab33e73809b767e51cdff93df7a8c" | ||
} |
import { | ||
CacheDescriptor, | ||
CacheDescriptorInternal, | ||
CacheDescriptorWithKey, | ||
NsFallback, | ||
@@ -10,5 +9,5 @@ TranslationsFlat, | ||
BackendGetRecordInternal, | ||
RecordFetchError, | ||
} from '../../types'; | ||
import { getFallbackArray, unique } from '../../helpers'; | ||
import { EventEmitterInstance } from '../Events/EventEmitter'; | ||
import { getFallbackArray, isPromise, unique } from '../../helpers'; | ||
import { TolgeeStaticData } from '../State/initState'; | ||
@@ -18,2 +17,3 @@ import { ValueObserverInstance } from '../ValueObserver'; | ||
import { decodeCacheKey, encodeCacheKey, flattenTranslations } from './helpers'; | ||
import { EventsInstance } from '../Events/Events'; | ||
@@ -33,3 +33,3 @@ type CacheAsyncRequests = Map< | ||
export function Cache( | ||
onCacheChange: EventEmitterInstance<CacheDescriptorWithKey>, | ||
events: EventsInstance, | ||
backendGetRecord: BackendGetRecordInternal, | ||
@@ -57,3 +57,3 @@ backendGetDevRecord: BackendGetRecordInternal, | ||
}); | ||
onCacheChange.emit(descriptor); | ||
events.onCacheChange.emit(descriptor); | ||
} | ||
@@ -65,27 +65,39 @@ | ||
function fetchProd(keyObject: CacheDescriptorInternal) { | ||
let dataPromise = undefined as | ||
let dataOrPromise = undefined as | ||
| Promise<TreeTranslationsData | undefined> | ||
| undefined; | ||
if (!dataPromise) { | ||
if (!dataOrPromise) { | ||
const staticDataValue = staticData[encodeCacheKey(keyObject)]; | ||
if (typeof staticDataValue === 'function') { | ||
dataPromise = staticDataValue(); | ||
dataOrPromise = staticDataValue(); | ||
} | ||
} | ||
if (!dataPromise) { | ||
dataPromise = backendGetRecord(keyObject); | ||
if (!dataOrPromise) { | ||
dataOrPromise = backendGetRecord(keyObject); | ||
} | ||
return dataPromise; | ||
if (isPromise(dataOrPromise)) { | ||
return dataOrPromise?.catch((e) => { | ||
const error = new RecordFetchError(keyObject, e); | ||
events.onError.emit(error); | ||
// eslint-disable-next-line no-console | ||
console.error(error); | ||
throw error; | ||
}); | ||
} else { | ||
return dataOrPromise; | ||
} | ||
} | ||
function fetchData(keyObject: CacheDescriptorInternal, isDev: boolean) { | ||
let dataPromise = undefined as | ||
let dataOrPromise = undefined as | ||
| Promise<TreeTranslationsData | undefined> | ||
| undefined; | ||
if (isDev) { | ||
dataPromise = backendGetDevRecord(keyObject)?.catch(() => { | ||
dataOrPromise = backendGetDevRecord(keyObject)?.catch((e) => { | ||
const error = new RecordFetchError(keyObject, e, true); | ||
events.onError.emit(error); | ||
// eslint-disable-next-line no-console | ||
console.warn(`Tolgee: Failed to fetch data from dev backend`); | ||
console.warn(error); | ||
// fallback to prod fetch if dev fails | ||
@@ -96,7 +108,7 @@ return fetchProd(keyObject); | ||
if (!dataPromise) { | ||
dataPromise = fetchProd(keyObject); | ||
if (!dataOrPromise) { | ||
dataOrPromise = fetchProd(keyObject); | ||
} | ||
return dataPromise; | ||
return dataOrPromise; | ||
} | ||
@@ -184,3 +196,3 @@ | ||
record?.set(key, value); | ||
onCacheChange.emit({ ...descriptor, key }); | ||
events.onCacheChange.emit({ ...descriptor, key }); | ||
}, | ||
@@ -187,0 +199,0 @@ |
@@ -9,3 +9,2 @@ import { Events } from './Events/Events'; | ||
KeyAndNamespacesInternal, | ||
TranslationDescriptor, | ||
} from '../types'; | ||
@@ -51,7 +50,7 @@ import { Cache } from './Cache/Cache'; | ||
changeTranslation, | ||
onPermanentChange | ||
events | ||
); | ||
const cache = Cache( | ||
events.onCacheChange, | ||
events, | ||
pluginService.getBackendRecord, | ||
@@ -115,9 +114,2 @@ pluginService.getBackendDevRecord, | ||
function onPermanentChange(props: TranslationDescriptor) { | ||
events.onPermanentChange.emit({ | ||
key: props.key, | ||
namespace: props.namespace, | ||
}); | ||
} | ||
function init(options: Partial<TolgeeOptions>) { | ||
@@ -188,2 +180,3 @@ state.init(options); | ||
const languageOrPromise = pluginService.getInitialLanguage(); | ||
return valueOrPromise(languageOrPromise, (lang) => { | ||
@@ -238,3 +231,3 @@ const language = | ||
state.setLanguage(language); | ||
pluginService.setStoredLanguage(language); | ||
await pluginService.setStoredLanguage(language); | ||
} | ||
@@ -241,0 +234,0 @@ }, |
@@ -5,2 +5,3 @@ import { EventEmitter } from './EventEmitter'; | ||
CacheDescriptorWithKey, | ||
TolgeeError, | ||
TolgeeOn, | ||
@@ -30,2 +31,3 @@ TranslationDescriptor, | ||
onPermanentChange: EventEmitter<TranslationDescriptor>(isActive), | ||
onError: EventEmitter<TolgeeError>(isActive), | ||
setEmitterActive(active: boolean) { | ||
@@ -54,2 +56,4 @@ emitterActive = active; | ||
return self.onPermanentChange.listen(handler as any); | ||
case 'error': | ||
return self.onError.listen(handler as any); | ||
} | ||
@@ -56,0 +60,0 @@ }) as TolgeeOn, |
@@ -1,3 +0,7 @@ | ||
import { getErrorMessage, isPromise, valueOrPromise } from '../../helpers'; | ||
import { | ||
getErrorMessage, | ||
valueOrPromise, | ||
handleRegularOrAsyncErr, | ||
} from '../../helpers'; | ||
import { | ||
BackendDevMiddleware, | ||
@@ -25,4 +29,6 @@ BackendMiddleware, | ||
BackendGetRecordInternal, | ||
TranslationDescriptor, | ||
LanguageStorageError, | ||
LanguageDetectorError, | ||
} from '../../types'; | ||
import { EventsInstance } from '../Events/Events'; | ||
import { DEFAULT_FORMAT_ERROR } from '../State/initState'; | ||
@@ -38,3 +44,3 @@ | ||
changeTranslation: ChangeTranslationInterface, | ||
onPermanentChange: (props: TranslationDescriptor) => void | ||
events: EventsInstance | ||
) { | ||
@@ -130,2 +136,10 @@ const plugins = { | ||
function storageLoadLanguage() { | ||
return handleRegularOrAsyncErr( | ||
events.onError, | ||
(e) => new LanguageStorageError('Tolgee: Failed to load language', e), | ||
() => instances.languageStorage?.getLanguage(getCommonProps()) | ||
); | ||
} | ||
function detectLanguage() { | ||
@@ -138,6 +152,11 @@ if (!instances.languageDetector) { | ||
return instances.languageDetector.getLanguage({ | ||
availableLanguages, | ||
...getCommonProps(), | ||
}); | ||
return handleRegularOrAsyncErr( | ||
events.onError, | ||
(e) => new LanguageDetectorError('Tolgee: Failed to detect language', e), | ||
() => | ||
instances.languageDetector?.getLanguage({ | ||
availableLanguages, | ||
...getCommonProps(), | ||
}) | ||
); | ||
} | ||
@@ -184,3 +203,3 @@ | ||
findPositions, | ||
onPermanentChange, | ||
onPermanentChange: (data) => events.onPermanentChange.emit(data), | ||
}); | ||
@@ -207,5 +226,3 @@ | ||
const availableLanguages = getAvailableLanguages(); | ||
const languageOrPromise = instances.languageStorage?.getLanguage( | ||
getCommonProps() | ||
); | ||
const languageOrPromise = storageLoadLanguage(); | ||
@@ -224,3 +241,7 @@ return valueOrPromise(languageOrPromise, (language) => { | ||
setStoredLanguage(language: string) { | ||
instances.languageStorage?.setLanguage(language, getCommonProps()); | ||
return handleRegularOrAsyncErr( | ||
events.onError, | ||
(e) => new LanguageStorageError('Tolgee: Failed to store language', e), | ||
() => instances.languageStorage?.setLanguage(language, getCommonProps()) | ||
); | ||
}, | ||
@@ -239,9 +260,2 @@ | ||
}); | ||
if (isPromise(data)) { | ||
return data?.catch((e) => { | ||
// eslint-disable-next-line no-console | ||
console.error(e); | ||
return {}; | ||
}); | ||
} | ||
if (data !== undefined) { | ||
@@ -248,0 +262,0 @@ return data; |
@@ -6,6 +6,10 @@ import { | ||
FetchFn, | ||
TolgeeError, | ||
} from './types'; | ||
import { EventEmitterInstance } from './Controller/Events/EventEmitter'; | ||
export function isPromise(value: any) { | ||
return Boolean(value && typeof value.then === 'function'); | ||
export function isPromise(value: unknown): value is Promise<unknown> { | ||
return Boolean( | ||
value && typeof (value as unknown as Promise<unknown>).then === 'function' | ||
); | ||
} | ||
@@ -24,2 +28,25 @@ | ||
export function handleRegularOrAsyncErr<T>( | ||
onError: EventEmitterInstance<TolgeeError>, | ||
createError: (e: any) => TolgeeError, | ||
callback: () => Promise<T> | T | ||
): Promise<T> | T { | ||
function handle(e: any): never { | ||
const error = createError(e); | ||
onError.emit(error); | ||
// eslint-disable-next-line no-console | ||
console.error(error); | ||
throw error; | ||
} | ||
try { | ||
const result = callback(); | ||
if (isPromise(result)) { | ||
return result.catch(handle); | ||
} | ||
return result; | ||
} catch (e) { | ||
handle(e); | ||
} | ||
} | ||
export function missingOptionError(option: string | string[]) { | ||
@@ -26,0 +53,0 @@ const options = (Array.isArray(option) ? option : [option]).map( |
import type { NsFallback } from './general'; | ||
import type { CacheDescriptorWithKey } from './cache'; | ||
import { TolgeeError } from './errors'; | ||
@@ -42,2 +43,3 @@ export type Subscription = { | ||
update: void; | ||
error: TolgeeError; | ||
permanentChange: CacheDescriptorWithKey; | ||
@@ -89,2 +91,7 @@ } | ||
/** | ||
* Emitted on errors | ||
*/ | ||
(event: 'error', handler: Listener<TolgeeError>): Subscription; | ||
/** | ||
* Translation was changed or created via dev tools | ||
@@ -91,0 +98,0 @@ */ |
@@ -5,2 +5,3 @@ export * from './general'; | ||
export * from './plugin'; | ||
export * from './errors'; | ||
@@ -7,0 +8,0 @@ export type { |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
No v1
QualityPackage is not semver >=1. This means it is not stable and does not support ^ ranges.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
991748
96
13478
1