@kivacore/i18n 0.0.0 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,119 @@
1
+ import * as react from 'react';
2
+ import { ReactNode } from 'react';
3
+ import { D as DocyrusI18nContextValue } from '../types-Bj3Uk0wv.js';
4
+ export { a as DocyrusI18nConfig, F as FallbackStrategy, I as I18nStatus, b as I18nStorageAdapter, T as TranslationDictionary, c as TranslationsResponse } from '../types-Bj3Uk0wv.js';
5
+ export { I as I18nManager, a as I18nStateListener, M as MemoryStorageAdapter, i as interpolate, t as translateValue } from '../locale-storage-DfFDJf0I.js';
6
+ import '@kivacore/api-client';
7
+
8
+ type SupportedLanguage = 'en' | 'tr';
9
+ /**
10
+ * RN i18n context value — extends core with `lang` / `setLanguage` aliases.
11
+ * `lang` and `setLanguage` are aliases for `locale` and `setLocale`
12
+ * to maintain backward compatibility with existing mobile code.
13
+ */
14
+ interface I18nContextValue extends DocyrusI18nContextValue {
15
+ /** Current language (alias for `locale`). Falls back to 'en'. */
16
+ lang: SupportedLanguage;
17
+ /** Change language (alias for `setLocale`). */
18
+ setLanguage: (lang: string) => void;
19
+ /** Reload translations from remote. */
20
+ reloadTranslations: () => Promise<void>;
21
+ }
22
+ /**
23
+ * React Native i18n hook with graceful fallback.
24
+ *
25
+ * Works with OR without `<DocyI18nProvider>`.
26
+ * When used outside a provider, returns a no-op `t()` that returns the key or fallback.
27
+ * This makes it safe to use in shared library components (e.g. @docyrus/ui-native).
28
+ *
29
+ * Returns: { t, tv, lang, locale, setLanguage, setLocale, status, isLoading, translations, error, refetch }
30
+ */
31
+ declare function useI18n(): I18nContextValue;
32
+ /**
33
+ * Strict i18n hook. Throws if used outside `<DocyI18nProvider>`.
34
+ * Use `useI18n()` for graceful fallback in library code.
35
+ */
36
+ declare function useDocyrusI18n(): I18nContextValue;
37
+ /**
38
+ * Lightweight hook for translation only.
39
+ * Works with OR without provider (graceful fallback).
40
+ */
41
+ declare function useTranslation(): {
42
+ t: (key: string, fallbackOrParams?: string | Record<string, string | number>) => string;
43
+ tv: (value: string) => string;
44
+ isLoading: boolean;
45
+ };
46
+ /**
47
+ * RN-specific storage adapter that wraps getString/setString pattern
48
+ * (used by MMKV, AsyncStorage wrappers) into the core I18nStorageAdapter.
49
+ */
50
+ type RNStorageAdapter = {
51
+ getString: (key: string) => string | undefined | null;
52
+ setString: (key: string, value: string) => void;
53
+ };
54
+ type RemoteTranslationItem = {
55
+ key: string;
56
+ en_US: string;
57
+ tr_TR: string;
58
+ [locale: string]: string;
59
+ };
60
+ type RemoteTranslationsResponse = {
61
+ primary?: RemoteTranslationItem[];
62
+ override?: RemoteTranslationItem[];
63
+ [key: string]: unknown;
64
+ };
65
+ type TranslationValue = string | {
66
+ [key: string]: TranslationValue;
67
+ };
68
+ type NestedTranslations = Record<string, TranslationValue>;
69
+ type DocyI18nProviderProps = {
70
+ children: ReactNode;
71
+ /** Function to fetch remote translations. */
72
+ fetchRemote?: () => Promise<RemoteTranslationsResponse | null>;
73
+ /** Default/fallback translations (nested format: { en: { common: { save: "Save" } }, tr: { ... } }). */
74
+ defaultTranslations?: Record<SupportedLanguage, NestedTranslations>;
75
+ /** Initial language. Default: 'en' */
76
+ defaultLanguage?: SupportedLanguage;
77
+ /** User's language from profile (e.g., "tr_TR", "en_US", "tr", "en"). Takes priority over saved preference. */
78
+ userLanguage?: string | null;
79
+ /** Storage adapter for persisting language preference (getString/setString pattern). */
80
+ storage?: RNStorageAdapter;
81
+ /** Storage key for persisting language preference. Default: '@kivacore/i18n/language' */
82
+ storageKey?: string;
83
+ /** Callback when language changes. */
84
+ onLanguageChange?: (lang: SupportedLanguage) => void;
85
+ /** Callback when translations are loaded. */
86
+ onTranslationsLoaded?: (translations: Record<SupportedLanguage, NestedTranslations>) => void;
87
+ /** Callback on error. */
88
+ onError?: (error: Error) => void;
89
+ };
90
+ /**
91
+ * React Native i18n provider.
92
+ *
93
+ * Backward-compatible with existing mobile API:
94
+ * - `fetchRemote` for API translations
95
+ * - `defaultTranslations` with nested format
96
+ * - `storage` with getString/setString pattern (MMKV compatible)
97
+ * - `userLanguage` for profile language sync
98
+ *
99
+ * Usage:
100
+ * ```tsx
101
+ * import { DocyI18nProvider } from '@kivacore/i18n/rn';
102
+ *
103
+ * <DocyI18nProvider
104
+ * fetchRemote={fetchTranslations}
105
+ * defaultTranslations={translations}
106
+ * defaultLanguage="tr"
107
+ * userLanguage={userData?.language}
108
+ * storage={storage}
109
+ * >
110
+ * <App />
111
+ * </DocyI18nProvider>
112
+ * ```
113
+ */
114
+ declare function DocyI18nProvider({ children, fetchRemote, defaultTranslations, defaultLanguage, userLanguage, storage, storageKey, onLanguageChange, onTranslationsLoaded, onError }: DocyI18nProviderProps): react.JSX.Element;
115
+ /** Alias for devkit naming convention. */
116
+ declare const DocyrusI18nProvider: typeof DocyI18nProvider;
117
+
118
+ export { DocyI18nProvider, DocyrusI18nContextValue, DocyrusI18nProvider, useDocyrusI18n, useI18n, useTranslation };
119
+ export type { DocyI18nProviderProps, I18nContextValue, RNStorageAdapter, SupportedLanguage };
@@ -0,0 +1,582 @@
1
+ import { createContext, use, useState, useRef, useEffect, useMemo, useCallback } from 'react';
2
+ import { jsx } from 'react/jsx-runtime';
3
+
4
+ // src/rn/index.tsx
5
+
6
+ // src/core/interpolation.ts
7
+ function interpolate(template, params) {
8
+ if (!params) return template;
9
+ return template.replace(
10
+ /\{\{(\w+)\}\}|\{(\w+)\}/g,
11
+ (match, doubleBraceKey, singleBraceKey) => {
12
+ const key = doubleBraceKey ?? singleBraceKey;
13
+ if (key === void 0) return match;
14
+ const value = params[key];
15
+ return value !== void 0 ? String(value) : match;
16
+ }
17
+ );
18
+ }
19
+
20
+ // src/core/locale-storage.ts
21
+ var DEFAULT_MAX_AGE = 365 * 24 * 60 * 60;
22
+ var CookieStorageAdapter = class {
23
+ constructor(cookieKey = "docyrus-locale") {
24
+ this.cookieKey = cookieKey;
25
+ }
26
+ cookieKey;
27
+ getLocale() {
28
+ if (typeof document === "undefined") return null;
29
+ const match = document.cookie.match(new RegExp(`(?:^|;\\s*)${escapeRegex(this.cookieKey)}=([^;]*)`));
30
+ return match ? decodeURIComponent(match[1]) : null;
31
+ }
32
+ setLocale(locale) {
33
+ if (typeof document === "undefined") return;
34
+ document.cookie = `${this.cookieKey}=${encodeURIComponent(locale)};path=/;max-age=${DEFAULT_MAX_AGE};SameSite=Lax`;
35
+ }
36
+ };
37
+ var MemoryStorageAdapter = class {
38
+ locale = null;
39
+ getLocale() {
40
+ return this.locale;
41
+ }
42
+ setLocale(locale) {
43
+ this.locale = locale;
44
+ }
45
+ };
46
+ function escapeRegex(str) {
47
+ return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
48
+ }
49
+
50
+ // src/core/translate-value.ts
51
+ function translateValue(value, t) {
52
+ if (!value.startsWith("translate.")) return value;
53
+ const raw = value.slice(10);
54
+ const key = `common.${raw.toLowerCase().replace(/\s+/g, "-")}`;
55
+ return t(key) === key ? raw : t(key);
56
+ }
57
+
58
+ // src/core/i18n-manager.ts
59
+ var I18nManager = class {
60
+ status = "loading";
61
+ locale;
62
+ translations = {};
63
+ apiTranslations = {};
64
+ error = null;
65
+ listeners = /* @__PURE__ */ new Set();
66
+ abortController = null;
67
+ client;
68
+ getAccessToken;
69
+ apiUrl;
70
+ translationsEndpoint;
71
+ staticTranslations;
72
+ storage;
73
+ mergeStrategy;
74
+ fallback;
75
+ disableApiFetch;
76
+ userLanguageEndpoint;
77
+ constructor(config) {
78
+ this.client = config.client ?? null;
79
+ this.getAccessToken = config.getAccessToken;
80
+ this.apiUrl = config.apiUrl;
81
+ this.translationsEndpoint = config.translationsEndpoint ?? "v1/tenant/translations";
82
+ this.staticTranslations = config.staticTranslations ?? {};
83
+ this.storage = config.storage ?? new CookieStorageAdapter(config.cookieKey ?? "docyrus-locale");
84
+ this.mergeStrategy = config.mergeStrategy ?? "api-first";
85
+ this.fallback = config.fallback ?? "key";
86
+ this.disableApiFetch = config.disableApiFetch ?? false;
87
+ this.userLanguageEndpoint = config.userLanguageEndpoint ?? "v1/users/me";
88
+ this.locale = this.storage.getLocale();
89
+ }
90
+ getStatus() {
91
+ return this.status;
92
+ }
93
+ getLocale() {
94
+ return this.locale;
95
+ }
96
+ getTranslations() {
97
+ return this.translations;
98
+ }
99
+ getError() {
100
+ return this.error;
101
+ }
102
+ subscribe(listener) {
103
+ this.listeners.add(listener);
104
+ return () => this.listeners.delete(listener);
105
+ }
106
+ notify() {
107
+ for (const listener of this.listeners) {
108
+ listener({
109
+ status: this.status,
110
+ locale: this.locale,
111
+ translations: this.translations,
112
+ error: this.error
113
+ });
114
+ }
115
+ }
116
+ /**
117
+ * Initialize the manager.
118
+ * 1. Apply static translations immediately (no loading flash).
119
+ * 2. Fetch from API if enabled and auth is available.
120
+ */
121
+ async initialize() {
122
+ if (Object.keys(this.staticTranslations).length > 0) {
123
+ this.translations = { ...this.staticTranslations };
124
+ this.status = "ready";
125
+ this.notify();
126
+ }
127
+ if (!this.disableApiFetch && (this.client || this.getAccessToken)) {
128
+ await this.fetchTranslations();
129
+ } else if (this.status !== "ready") {
130
+ this.status = "ready";
131
+ this.notify();
132
+ }
133
+ }
134
+ /**
135
+ * Fetch translations from the API.
136
+ * Uses RestApiClient.get() if client is available, otherwise raw fetch with getAccessToken.
137
+ */
138
+ async fetchTranslations() {
139
+ this.abortController?.abort();
140
+ this.abortController = new AbortController();
141
+ try {
142
+ let apiData;
143
+ if (this.client) {
144
+ apiData = await this.client.get(
145
+ this.translationsEndpoint
146
+ );
147
+ } else if (this.getAccessToken && this.apiUrl) {
148
+ const token = await this.getAccessToken();
149
+ if (!token) {
150
+ throw new Error("getAccessToken returned null \u2014 cannot fetch translations");
151
+ }
152
+ const url = `${this.apiUrl.replace(/\/$/, "")}/${this.translationsEndpoint}`;
153
+ const res = await fetch(url, {
154
+ headers: { Authorization: `Bearer ${token}` },
155
+ signal: this.abortController.signal
156
+ });
157
+ if (!res.ok) {
158
+ throw new Error(`Translation fetch failed: ${res.status} ${res.statusText}`);
159
+ }
160
+ apiData = await res.json();
161
+ } else {
162
+ return;
163
+ }
164
+ this.apiTranslations = apiData.data;
165
+ this.mergeTranslations();
166
+ this.error = null;
167
+ this.status = "ready";
168
+ this.notify();
169
+ } catch (err) {
170
+ if (err.name === "AbortError") return;
171
+ this.error = err instanceof Error ? err : new Error(String(err));
172
+ if (Object.keys(this.translations).length > 0) {
173
+ this.notify();
174
+ } else {
175
+ this.status = "error";
176
+ this.notify();
177
+ }
178
+ }
179
+ }
180
+ /**
181
+ * Translate a key.
182
+ * - `t('key')` — returns translated value or key itself
183
+ * - `t('key', 'Fallback')` — returns translated value or fallback string
184
+ * - `t('key', { name: 'Ali' })` — returns interpolated value with params
185
+ */
186
+ t(key, fallbackOrParams) {
187
+ const isParams = typeof fallbackOrParams === "object";
188
+ const params = isParams ? fallbackOrParams : void 0;
189
+ const fallbackStr = typeof fallbackOrParams === "string" ? fallbackOrParams : void 0;
190
+ const value = this.translations[key];
191
+ if (value !== void 0) {
192
+ return interpolate(value, params);
193
+ }
194
+ if (fallbackStr !== void 0) return fallbackStr;
195
+ if (this.fallback === "key") return interpolate(key, params);
196
+ if (this.fallback === "empty") return "";
197
+ return this.fallback(key);
198
+ }
199
+ /**
200
+ * Translate API response values with "translate." prefix.
201
+ * e.g. tv('translate.Active') → 'Aktif'
202
+ */
203
+ tv(value) {
204
+ return translateValue(value, (key, params) => this.t(key, params));
205
+ }
206
+ /**
207
+ * Change the active locale.
208
+ * Persists to storage, updates API (PATCH users/me), and triggers translation refetch.
209
+ */
210
+ async setLocale(locale) {
211
+ if (locale === this.locale) return;
212
+ this.locale = locale;
213
+ this.storage.setLocale(locale);
214
+ this.notify();
215
+ const promises = [];
216
+ if (this.userLanguageEndpoint !== false && (this.client || this.getAccessToken)) {
217
+ promises.push(this.persistUserLanguage(locale));
218
+ }
219
+ if (!this.disableApiFetch && (this.client || this.getAccessToken)) {
220
+ promises.push(this.fetchTranslations());
221
+ }
222
+ await Promise.all(promises);
223
+ }
224
+ /**
225
+ * Persist user language preference to API.
226
+ * PATCH {userLanguageEndpoint} { language: locale }
227
+ */
228
+ async persistUserLanguage(locale) {
229
+ if (this.userLanguageEndpoint === false) return;
230
+ try {
231
+ if (this.client) {
232
+ await this.client.patch(this.userLanguageEndpoint, { language: locale });
233
+ } else if (this.getAccessToken && this.apiUrl) {
234
+ const token = await this.getAccessToken();
235
+ if (!token) return;
236
+ const url = `${this.apiUrl.replace(/\/$/, "")}/${this.userLanguageEndpoint}`;
237
+ await fetch(url, {
238
+ method: "PATCH",
239
+ headers: {
240
+ Authorization: `Bearer ${token}`,
241
+ "Content-Type": "application/json"
242
+ },
243
+ body: JSON.stringify({ language: locale })
244
+ });
245
+ }
246
+ } catch {
247
+ }
248
+ }
249
+ /**
250
+ * Update config at runtime.
251
+ * Useful when client transitions from null → RestApiClient (auth loading complete).
252
+ */
253
+ updateConfig(updates) {
254
+ let shouldFetch = false;
255
+ if (updates.client !== void 0 && updates.client !== this.client) {
256
+ const hadNoClient = !this.client;
257
+ this.client = updates.client;
258
+ if (hadNoClient && this.client && !this.disableApiFetch) {
259
+ shouldFetch = true;
260
+ }
261
+ }
262
+ if (updates.staticTranslations !== void 0) {
263
+ this.staticTranslations = updates.staticTranslations;
264
+ this.mergeTranslations();
265
+ this.notify();
266
+ }
267
+ if (shouldFetch) {
268
+ this.fetchTranslations();
269
+ }
270
+ }
271
+ /** Cleanup: abort in-flight requests + clear listeners. */
272
+ destroy() {
273
+ this.abortController?.abort();
274
+ this.listeners.clear();
275
+ }
276
+ mergeTranslations() {
277
+ if (this.mergeStrategy === "api-first") {
278
+ this.translations = { ...this.staticTranslations, ...this.apiTranslations };
279
+ } else {
280
+ this.translations = { ...this.apiTranslations, ...this.staticTranslations };
281
+ }
282
+ }
283
+ };
284
+ var DocyrusI18nRNContext = createContext(null);
285
+ var fallbackT = (key, fallbackOrParams) => {
286
+ if (typeof fallbackOrParams === "string") return fallbackOrParams;
287
+ return key;
288
+ };
289
+ var fallbackTv = (value) => value;
290
+ var fallbackSetLocale = () => {
291
+ };
292
+ var fallbackRefetch = async () => {
293
+ };
294
+ var fallbackContext = {
295
+ t: fallbackT,
296
+ tv: fallbackTv,
297
+ locale: null,
298
+ lang: "en",
299
+ setLocale: fallbackSetLocale,
300
+ setLanguage: fallbackSetLocale,
301
+ status: "ready",
302
+ isLoading: false,
303
+ translations: {},
304
+ error: null,
305
+ refetch: fallbackRefetch,
306
+ reloadTranslations: fallbackRefetch
307
+ };
308
+ function useI18n() {
309
+ const context = use(DocyrusI18nRNContext);
310
+ return context ?? fallbackContext;
311
+ }
312
+ function useDocyrusI18n() {
313
+ const context = use(DocyrusI18nRNContext);
314
+ if (!context) {
315
+ throw new Error(
316
+ "useDocyrusI18n() must be used within a <DocyI18nProvider>. Use useI18n() for graceful fallback in library code."
317
+ );
318
+ }
319
+ return context;
320
+ }
321
+ function useTranslation() {
322
+ const { t, tv, isLoading } = useI18n();
323
+ return { t, tv, isLoading };
324
+ }
325
+ var parseUserLanguage = (userLang) => {
326
+ if (!userLang) return null;
327
+ const normalized = userLang.toLowerCase().trim();
328
+ if (normalized.startsWith("tr")) return "tr";
329
+ if (normalized.startsWith("en")) return "en";
330
+ return null;
331
+ };
332
+ var flattenTranslations = (obj, prefix = "") => {
333
+ const result = {};
334
+ for (const [key, value] of Object.entries(obj)) {
335
+ const fullKey = prefix ? `${prefix}.${key}` : key;
336
+ if (typeof value === "string") {
337
+ result[fullKey] = value;
338
+ } else if (typeof value === "object" && value !== null) {
339
+ Object.assign(result, flattenTranslations(value, fullKey));
340
+ }
341
+ }
342
+ return result;
343
+ };
344
+ var transformRemoteTranslations = (items) => {
345
+ const result = { en: {}, tr: {} };
346
+ for (const item of items) {
347
+ if (item.key) {
348
+ result.en[item.key] = item.en_US || item.key;
349
+ result.tr[item.key] = item.tr_TR || item.en_US || item.key;
350
+ }
351
+ }
352
+ return result;
353
+ };
354
+ var STORAGE_KEY_LANGUAGE = "@kivacore/i18n/language";
355
+ function DocyI18nProvider({
356
+ children,
357
+ fetchRemote,
358
+ defaultTranslations = { en: {}, tr: {} },
359
+ defaultLanguage = "en",
360
+ userLanguage,
361
+ storage,
362
+ storageKey = STORAGE_KEY_LANGUAGE,
363
+ onLanguageChange,
364
+ onTranslationsLoaded,
365
+ onError
366
+ }) {
367
+ const [lang, setLang] = useState(defaultLanguage);
368
+ const [allTranslations, setAllTranslations] = useState(defaultTranslations);
369
+ const [isLoading, setIsLoading] = useState(true);
370
+ const [error, setError] = useState(null);
371
+ const [isInitialized, setIsInitialized] = useState(false);
372
+ const storageRef = useRef(storage);
373
+ const onTranslationsLoadedRef = useRef(onTranslationsLoaded);
374
+ const onErrorRef = useRef(onError);
375
+ const defaultTranslationsRef = useRef(defaultTranslations);
376
+ storageRef.current = storage;
377
+ onTranslationsLoadedRef.current = onTranslationsLoaded;
378
+ onErrorRef.current = onError;
379
+ defaultTranslationsRef.current = defaultTranslations;
380
+ useEffect(() => {
381
+ if (!isInitialized) return;
382
+ const parsedUserLang = parseUserLanguage(userLanguage);
383
+ if (parsedUserLang && parsedUserLang !== lang) {
384
+ setLang(parsedUserLang);
385
+ const currentStorage = storageRef.current;
386
+ if (currentStorage) {
387
+ currentStorage.setString(storageKey, parsedUserLang);
388
+ }
389
+ }
390
+ }, [
391
+ userLanguage,
392
+ isInitialized,
393
+ storageKey,
394
+ lang
395
+ ]);
396
+ useEffect(() => {
397
+ try {
398
+ const currentStorage = storageRef.current;
399
+ if (currentStorage) {
400
+ const savedLang = currentStorage.getString(storageKey);
401
+ if (savedLang && (savedLang === "en" || savedLang === "tr")) {
402
+ setLang(savedLang);
403
+ } else {
404
+ const parsedUserLang = parseUserLanguage(userLanguage);
405
+ if (parsedUserLang) {
406
+ setLang(parsedUserLang);
407
+ currentStorage.setString(storageKey, parsedUserLang);
408
+ }
409
+ }
410
+ } else {
411
+ const parsedUserLang = parseUserLanguage(userLanguage);
412
+ if (parsedUserLang) {
413
+ setLang(parsedUserLang);
414
+ }
415
+ }
416
+ } finally {
417
+ setIsInitialized(true);
418
+ }
419
+ }, [storageKey, userLanguage]);
420
+ useEffect(() => {
421
+ if (!isInitialized || !fetchRemote) {
422
+ if (isInitialized) setIsLoading(false);
423
+ return;
424
+ }
425
+ const loadRemote = async () => {
426
+ try {
427
+ setIsLoading(true);
428
+ setError(null);
429
+ const data = await fetchRemote();
430
+ if (!data) {
431
+ setIsLoading(false);
432
+ return;
433
+ }
434
+ const primaryTransformed = data.primary ? transformRemoteTranslations(data.primary) : { en: {}, tr: {} };
435
+ const overrideTransformed = data.override ? transformRemoteTranslations(data.override) : { en: {}, tr: {} };
436
+ const remoteTranslations = {
437
+ en: { common: { ...primaryTransformed.en, ...overrideTransformed.en } },
438
+ tr: { common: { ...primaryTransformed.tr, ...overrideTransformed.tr } }
439
+ };
440
+ const defaults = defaultTranslationsRef.current;
441
+ const merged = {
442
+ en: deepMerge(defaults.en, remoteTranslations.en),
443
+ tr: deepMerge(defaults.tr, remoteTranslations.tr)
444
+ };
445
+ setAllTranslations(merged);
446
+ onTranslationsLoadedRef.current?.(merged);
447
+ } catch (err) {
448
+ const fetchError = err instanceof Error ? err : new Error(String(err));
449
+ setError(fetchError);
450
+ onErrorRef.current?.(fetchError);
451
+ } finally {
452
+ setIsLoading(false);
453
+ }
454
+ };
455
+ loadRemote();
456
+ }, [isInitialized, fetchRemote]);
457
+ const flatTranslations = useMemo(
458
+ () => flattenTranslations(allTranslations[lang] || {}),
459
+ [allTranslations, lang]
460
+ );
461
+ const t = useCallback(
462
+ (key, fallbackOrParams) => {
463
+ const value2 = flatTranslations[key];
464
+ if (value2 !== void 0) {
465
+ if (typeof fallbackOrParams === "object") {
466
+ return value2.replace(
467
+ /\{\{(\w+)\}\}|\{(\w+)\}/g,
468
+ (match, doubleBrace, singleBrace) => {
469
+ const paramKey = doubleBrace ?? singleBrace;
470
+ if (paramKey === void 0) return match;
471
+ const paramValue = fallbackOrParams[paramKey];
472
+ return paramValue !== void 0 ? String(paramValue) : match;
473
+ }
474
+ );
475
+ }
476
+ return value2;
477
+ }
478
+ if (typeof fallbackOrParams === "string") return fallbackOrParams;
479
+ return key;
480
+ },
481
+ [flatTranslations]
482
+ );
483
+ const tv = useCallback(
484
+ (value2) => {
485
+ if (typeof value2 !== "string") return String(value2 ?? "");
486
+ if (value2.startsWith("translate.")) {
487
+ const raw = value2.slice(10);
488
+ const key = `common.${raw}`;
489
+ const translated = flatTranslations[key];
490
+ return translated ?? raw;
491
+ }
492
+ return value2;
493
+ },
494
+ [flatTranslations]
495
+ );
496
+ const setLanguage = useCallback((newLang) => {
497
+ setLang(newLang);
498
+ const currentStorage = storageRef.current;
499
+ if (currentStorage) {
500
+ currentStorage.setString(storageKey, newLang);
501
+ }
502
+ onLanguageChange?.(newLang);
503
+ }, [storageKey, onLanguageChange]);
504
+ const reloadTranslations = useCallback(async () => {
505
+ if (!fetchRemote) return;
506
+ try {
507
+ setIsLoading(true);
508
+ setError(null);
509
+ const data = await fetchRemote();
510
+ if (!data) return;
511
+ const primaryTransformed = data.primary ? transformRemoteTranslations(data.primary) : { en: {}, tr: {} };
512
+ const overrideTransformed = data.override ? transformRemoteTranslations(data.override) : { en: {}, tr: {} };
513
+ const remoteTranslations = {
514
+ en: { common: { ...primaryTransformed.en, ...overrideTransformed.en } },
515
+ tr: { common: { ...primaryTransformed.tr, ...overrideTransformed.tr } }
516
+ };
517
+ const merged = {
518
+ en: deepMerge(defaultTranslations.en, remoteTranslations.en),
519
+ tr: deepMerge(defaultTranslations.tr, remoteTranslations.tr)
520
+ };
521
+ setAllTranslations(merged);
522
+ onTranslationsLoaded?.(merged);
523
+ } catch (err) {
524
+ const fetchError = err instanceof Error ? err : new Error(String(err));
525
+ setError(fetchError);
526
+ onError?.(fetchError);
527
+ } finally {
528
+ setIsLoading(false);
529
+ }
530
+ }, [
531
+ fetchRemote,
532
+ defaultTranslations,
533
+ onTranslationsLoaded,
534
+ onError
535
+ ]);
536
+ const value = useMemo(() => ({
537
+ t,
538
+ tv,
539
+ locale: lang,
540
+ lang,
541
+ setLocale: setLanguage,
542
+ setLanguage,
543
+ status: isLoading ? "loading" : error ? "error" : "ready",
544
+ isLoading,
545
+ translations: flatTranslations,
546
+ error,
547
+ refetch: reloadTranslations,
548
+ reloadTranslations
549
+ }), [
550
+ t,
551
+ tv,
552
+ lang,
553
+ setLanguage,
554
+ isLoading,
555
+ flatTranslations,
556
+ error,
557
+ reloadTranslations
558
+ ]);
559
+ return /* @__PURE__ */ jsx(DocyrusI18nRNContext, { value, children });
560
+ }
561
+ var DocyrusI18nProvider = DocyI18nProvider;
562
+ function deepMerge(target, source) {
563
+ const result = { ...target };
564
+ for (const key of Object.keys(source)) {
565
+ const sourceValue = source[key];
566
+ const targetValue = result[key];
567
+ if (sourceValue === void 0) continue;
568
+ if (typeof sourceValue === "object" && sourceValue !== null && typeof targetValue === "object" && targetValue !== null) {
569
+ result[key] = deepMerge(
570
+ targetValue,
571
+ sourceValue
572
+ );
573
+ } else {
574
+ result[key] = sourceValue;
575
+ }
576
+ }
577
+ return result;
578
+ }
579
+
580
+ export { DocyI18nProvider, DocyrusI18nProvider, I18nManager, MemoryStorageAdapter, interpolate, translateValue, useDocyrusI18n, useI18n, useTranslation };
581
+ //# sourceMappingURL=index.js.map
582
+ //# sourceMappingURL=index.js.map