@docyrus/i18n 0.0.1
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.
- package/README.md +283 -0
- package/dist/core-index.d.ts +107 -0
- package/dist/core-index.js +246 -0
- package/dist/core-index.js.map +1 -0
- package/dist/index.d.ts +34 -0
- package/dist/index.js +340 -0
- package/dist/index.js.map +1 -0
- package/dist/types-DQtgewNG.d.ts +55 -0
- package/dist/vue/index.d.ts +136 -0
- package/dist/vue/index.js +350 -0
- package/dist/vue/index.js.map +1 -0
- package/package.json +62 -0
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
2
|
+
import * as react from 'react';
|
|
3
|
+
import { ReactNode } from 'react';
|
|
4
|
+
import { D as DocyrusI18nConfig, a as DocyrusI18nContextValue } from './types-DQtgewNG.js';
|
|
5
|
+
export { F as FallbackStrategy, I as I18nStatus, T as TranslationDictionary, b as TranslationsResponse } from './types-DQtgewNG.js';
|
|
6
|
+
export { I18nManager, I18nStateListener, getLocale, interpolate, setLocale } from './core-index.js';
|
|
7
|
+
import '@docyrus/api-client';
|
|
8
|
+
|
|
9
|
+
declare const DocyrusI18nContext: react.Context<DocyrusI18nContextValue | null>;
|
|
10
|
+
interface DocyrusI18nProviderProps extends DocyrusI18nConfig {
|
|
11
|
+
children: ReactNode;
|
|
12
|
+
}
|
|
13
|
+
declare function DocyrusI18nProvider({ children, ...config }: DocyrusI18nProviderProps): react_jsx_runtime.JSX.Element;
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Access the full Docyrus i18n context.
|
|
17
|
+
* Must be used within a `<DocyrusI18nProvider>`.
|
|
18
|
+
*
|
|
19
|
+
* Returns: { t, locale, setLocale, status, isLoading, translations, error, refetch }
|
|
20
|
+
*/
|
|
21
|
+
declare function useDocyrusI18n(): DocyrusI18nContextValue;
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Lightweight hook for translation only.
|
|
25
|
+
* Returns just `t` and `isLoading` — use `useDocyrusI18n()` for full context.
|
|
26
|
+
*
|
|
27
|
+
* Must be used within a `<DocyrusI18nProvider>`.
|
|
28
|
+
*/
|
|
29
|
+
declare function useTranslation(): {
|
|
30
|
+
t: (key: string, params?: Record<string, string | number>) => string;
|
|
31
|
+
isLoading: boolean;
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
export { DocyrusI18nConfig, DocyrusI18nContext, DocyrusI18nContextValue, DocyrusI18nProvider, type DocyrusI18nProviderProps, useDocyrusI18n, useTranslation };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
import { createContext, useState, useRef, useEffect, useCallback, useMemo, useContext } from 'react';
|
|
2
|
+
import { jsx } from 'react/jsx-runtime';
|
|
3
|
+
|
|
4
|
+
// src/components/docyrus-i18n-provider.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
|
+
function getLocale(cookieKey) {
|
|
23
|
+
if (typeof document === "undefined") return null;
|
|
24
|
+
const match = document.cookie.match(new RegExp(`(?:^|;\\s*)${escapeRegex(cookieKey)}=([^;]*)`));
|
|
25
|
+
return match ? decodeURIComponent(match[1]) : null;
|
|
26
|
+
}
|
|
27
|
+
function setLocale(cookieKey, locale) {
|
|
28
|
+
if (typeof document === "undefined") return;
|
|
29
|
+
document.cookie = `${cookieKey}=${encodeURIComponent(locale)};path=/;max-age=${DEFAULT_MAX_AGE};SameSite=Lax`;
|
|
30
|
+
}
|
|
31
|
+
function escapeRegex(str) {
|
|
32
|
+
return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// src/core/i18n-manager.ts
|
|
36
|
+
var I18nManager = class {
|
|
37
|
+
status = "loading";
|
|
38
|
+
locale;
|
|
39
|
+
translations = {};
|
|
40
|
+
apiTranslations = {};
|
|
41
|
+
error = null;
|
|
42
|
+
listeners = /* @__PURE__ */ new Set();
|
|
43
|
+
abortController = null;
|
|
44
|
+
client;
|
|
45
|
+
getAccessToken;
|
|
46
|
+
apiUrl;
|
|
47
|
+
translationsEndpoint;
|
|
48
|
+
staticTranslations;
|
|
49
|
+
cookieKey;
|
|
50
|
+
mergeStrategy;
|
|
51
|
+
fallback;
|
|
52
|
+
disableApiFetch;
|
|
53
|
+
userLanguageEndpoint;
|
|
54
|
+
constructor(config) {
|
|
55
|
+
this.client = config.client ?? null;
|
|
56
|
+
this.getAccessToken = config.getAccessToken;
|
|
57
|
+
this.apiUrl = config.apiUrl;
|
|
58
|
+
this.translationsEndpoint = config.translationsEndpoint ?? "tenant/translations";
|
|
59
|
+
this.staticTranslations = config.staticTranslations ?? {};
|
|
60
|
+
this.cookieKey = config.cookieKey ?? "docyrus-locale";
|
|
61
|
+
this.mergeStrategy = config.mergeStrategy ?? "api-first";
|
|
62
|
+
this.fallback = config.fallback ?? "key";
|
|
63
|
+
this.disableApiFetch = config.disableApiFetch ?? false;
|
|
64
|
+
this.userLanguageEndpoint = config.userLanguageEndpoint ?? "users/me";
|
|
65
|
+
this.locale = getLocale(this.cookieKey);
|
|
66
|
+
}
|
|
67
|
+
getStatus() {
|
|
68
|
+
return this.status;
|
|
69
|
+
}
|
|
70
|
+
getLocale() {
|
|
71
|
+
return this.locale;
|
|
72
|
+
}
|
|
73
|
+
getTranslations() {
|
|
74
|
+
return this.translations;
|
|
75
|
+
}
|
|
76
|
+
getError() {
|
|
77
|
+
return this.error;
|
|
78
|
+
}
|
|
79
|
+
subscribe(listener) {
|
|
80
|
+
this.listeners.add(listener);
|
|
81
|
+
return () => this.listeners.delete(listener);
|
|
82
|
+
}
|
|
83
|
+
notify() {
|
|
84
|
+
for (const listener of this.listeners) {
|
|
85
|
+
listener({
|
|
86
|
+
status: this.status,
|
|
87
|
+
locale: this.locale,
|
|
88
|
+
translations: this.translations,
|
|
89
|
+
error: this.error
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Initialize the manager.
|
|
95
|
+
* 1. Apply static translations immediately (no loading flash).
|
|
96
|
+
* 2. Fetch from API if enabled and auth is available.
|
|
97
|
+
*/
|
|
98
|
+
async initialize() {
|
|
99
|
+
if (Object.keys(this.staticTranslations).length > 0) {
|
|
100
|
+
this.translations = { ...this.staticTranslations };
|
|
101
|
+
this.status = "ready";
|
|
102
|
+
this.notify();
|
|
103
|
+
}
|
|
104
|
+
if (!this.disableApiFetch && (this.client || this.getAccessToken)) {
|
|
105
|
+
await this.fetchTranslations();
|
|
106
|
+
} else if (this.status !== "ready") {
|
|
107
|
+
this.status = "ready";
|
|
108
|
+
this.notify();
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Fetch translations from the API.
|
|
113
|
+
* Uses RestApiClient.get() if client is available, otherwise raw fetch with getAccessToken.
|
|
114
|
+
*/
|
|
115
|
+
async fetchTranslations() {
|
|
116
|
+
this.abortController?.abort();
|
|
117
|
+
this.abortController = new AbortController();
|
|
118
|
+
try {
|
|
119
|
+
let apiData;
|
|
120
|
+
if (this.client) {
|
|
121
|
+
apiData = await this.client.get(
|
|
122
|
+
this.translationsEndpoint
|
|
123
|
+
);
|
|
124
|
+
} else if (this.getAccessToken && this.apiUrl) {
|
|
125
|
+
const token = await this.getAccessToken();
|
|
126
|
+
if (!token) {
|
|
127
|
+
throw new Error("getAccessToken returned null \u2014 cannot fetch translations");
|
|
128
|
+
}
|
|
129
|
+
const url = `${this.apiUrl.replace(/\/$/, "")}/${this.translationsEndpoint}`;
|
|
130
|
+
const res = await fetch(url, {
|
|
131
|
+
headers: { Authorization: `Bearer ${token}` },
|
|
132
|
+
signal: this.abortController.signal
|
|
133
|
+
});
|
|
134
|
+
if (!res.ok) {
|
|
135
|
+
throw new Error(`Translation fetch failed: ${res.status} ${res.statusText}`);
|
|
136
|
+
}
|
|
137
|
+
apiData = await res.json();
|
|
138
|
+
} else {
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
this.apiTranslations = apiData.data;
|
|
142
|
+
this.mergeTranslations();
|
|
143
|
+
this.error = null;
|
|
144
|
+
this.status = "ready";
|
|
145
|
+
this.notify();
|
|
146
|
+
} catch (err) {
|
|
147
|
+
if (err.name === "AbortError") return;
|
|
148
|
+
this.error = err instanceof Error ? err : new Error(String(err));
|
|
149
|
+
if (Object.keys(this.translations).length > 0) {
|
|
150
|
+
this.notify();
|
|
151
|
+
} else {
|
|
152
|
+
this.status = "error";
|
|
153
|
+
this.notify();
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* Translate a key with optional interpolation.
|
|
159
|
+
* Falls back based on the configured strategy.
|
|
160
|
+
*/
|
|
161
|
+
t(key, params) {
|
|
162
|
+
const value = this.translations[key];
|
|
163
|
+
if (value !== void 0) {
|
|
164
|
+
return interpolate(value, params);
|
|
165
|
+
}
|
|
166
|
+
if (this.fallback === "key") return key;
|
|
167
|
+
if (this.fallback === "empty") return "";
|
|
168
|
+
return this.fallback(key);
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* Change the active locale.
|
|
172
|
+
* Writes to cookie, persists to API (PATCH users/me), and triggers translation refetch.
|
|
173
|
+
*/
|
|
174
|
+
async setLocale(locale) {
|
|
175
|
+
if (locale === this.locale) return;
|
|
176
|
+
this.locale = locale;
|
|
177
|
+
setLocale(this.cookieKey, locale);
|
|
178
|
+
this.notify();
|
|
179
|
+
const promises = [];
|
|
180
|
+
if (this.userLanguageEndpoint !== false && (this.client || this.getAccessToken)) {
|
|
181
|
+
promises.push(this.persistUserLanguage(locale));
|
|
182
|
+
}
|
|
183
|
+
if (!this.disableApiFetch && (this.client || this.getAccessToken)) {
|
|
184
|
+
promises.push(this.fetchTranslations());
|
|
185
|
+
}
|
|
186
|
+
await Promise.all(promises);
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* Persist user language preference to API.
|
|
190
|
+
* PATCH {userLanguageEndpoint} { language: locale }
|
|
191
|
+
*/
|
|
192
|
+
async persistUserLanguage(locale) {
|
|
193
|
+
if (this.userLanguageEndpoint === false) return;
|
|
194
|
+
try {
|
|
195
|
+
if (this.client) {
|
|
196
|
+
await this.client.patch(this.userLanguageEndpoint, { language: locale });
|
|
197
|
+
} else if (this.getAccessToken && this.apiUrl) {
|
|
198
|
+
const token = await this.getAccessToken();
|
|
199
|
+
if (!token) return;
|
|
200
|
+
const url = `${this.apiUrl.replace(/\/$/, "")}/${this.userLanguageEndpoint}`;
|
|
201
|
+
await fetch(url, {
|
|
202
|
+
method: "PATCH",
|
|
203
|
+
headers: {
|
|
204
|
+
Authorization: `Bearer ${token}`,
|
|
205
|
+
"Content-Type": "application/json"
|
|
206
|
+
},
|
|
207
|
+
body: JSON.stringify({ language: locale })
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
} catch {
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
/**
|
|
214
|
+
* Update config at runtime.
|
|
215
|
+
* Useful when client transitions from null → RestApiClient (auth loading complete).
|
|
216
|
+
*/
|
|
217
|
+
updateConfig(updates) {
|
|
218
|
+
let shouldFetch = false;
|
|
219
|
+
if (updates.client !== void 0 && updates.client !== this.client) {
|
|
220
|
+
const hadNoClient = !this.client;
|
|
221
|
+
this.client = updates.client;
|
|
222
|
+
if (hadNoClient && this.client && !this.disableApiFetch) {
|
|
223
|
+
shouldFetch = true;
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
if (updates.staticTranslations !== void 0) {
|
|
227
|
+
this.staticTranslations = updates.staticTranslations;
|
|
228
|
+
this.mergeTranslations();
|
|
229
|
+
this.notify();
|
|
230
|
+
}
|
|
231
|
+
if (shouldFetch) {
|
|
232
|
+
this.fetchTranslations();
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
/** Cleanup: abort in-flight requests + clear listeners. */
|
|
236
|
+
destroy() {
|
|
237
|
+
this.abortController?.abort();
|
|
238
|
+
this.listeners.clear();
|
|
239
|
+
}
|
|
240
|
+
mergeTranslations() {
|
|
241
|
+
if (this.mergeStrategy === "api-first") {
|
|
242
|
+
this.translations = { ...this.staticTranslations, ...this.apiTranslations };
|
|
243
|
+
} else {
|
|
244
|
+
this.translations = { ...this.apiTranslations, ...this.staticTranslations };
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
};
|
|
248
|
+
var DocyrusI18nContext = createContext(null);
|
|
249
|
+
function DocyrusI18nProvider({
|
|
250
|
+
children,
|
|
251
|
+
...config
|
|
252
|
+
}) {
|
|
253
|
+
const [status, setStatus] = useState(
|
|
254
|
+
config.staticTranslations && Object.keys(config.staticTranslations).length > 0 ? "ready" : "loading"
|
|
255
|
+
);
|
|
256
|
+
const [locale, setLocaleState] = useState(null);
|
|
257
|
+
const [translations, setTranslations] = useState(
|
|
258
|
+
config.staticTranslations ?? {}
|
|
259
|
+
);
|
|
260
|
+
const [error, setError] = useState(null);
|
|
261
|
+
const managerRef = useRef(null);
|
|
262
|
+
useEffect(() => {
|
|
263
|
+
const manager = new I18nManager(config);
|
|
264
|
+
managerRef.current = manager;
|
|
265
|
+
setLocaleState(manager.getLocale());
|
|
266
|
+
const unsubscribe = manager.subscribe((state) => {
|
|
267
|
+
setStatus(state.status);
|
|
268
|
+
setLocaleState(state.locale);
|
|
269
|
+
setTranslations(state.translations);
|
|
270
|
+
setError(state.error);
|
|
271
|
+
});
|
|
272
|
+
manager.initialize();
|
|
273
|
+
return () => {
|
|
274
|
+
unsubscribe();
|
|
275
|
+
manager.destroy();
|
|
276
|
+
};
|
|
277
|
+
}, []);
|
|
278
|
+
const clientRef = useRef(config.client);
|
|
279
|
+
useEffect(() => {
|
|
280
|
+
if (config.client !== clientRef.current) {
|
|
281
|
+
clientRef.current = config.client;
|
|
282
|
+
managerRef.current?.updateConfig({ client: config.client });
|
|
283
|
+
}
|
|
284
|
+
}, [config.client]);
|
|
285
|
+
const setLocale2 = useCallback((newLocale) => {
|
|
286
|
+
managerRef.current?.setLocale(newLocale);
|
|
287
|
+
}, []);
|
|
288
|
+
const refetch = useCallback(async () => {
|
|
289
|
+
await managerRef.current?.fetchTranslations();
|
|
290
|
+
}, []);
|
|
291
|
+
const t = useCallback(
|
|
292
|
+
(key, params) => {
|
|
293
|
+
return managerRef.current?.t(key, params) ?? key;
|
|
294
|
+
},
|
|
295
|
+
// Re-create t when translations change so consumers re-render
|
|
296
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
297
|
+
[translations]
|
|
298
|
+
);
|
|
299
|
+
const value = useMemo(() => ({
|
|
300
|
+
t,
|
|
301
|
+
locale,
|
|
302
|
+
setLocale: setLocale2,
|
|
303
|
+
status,
|
|
304
|
+
isLoading: status === "loading",
|
|
305
|
+
translations,
|
|
306
|
+
error,
|
|
307
|
+
refetch
|
|
308
|
+
}), [
|
|
309
|
+
t,
|
|
310
|
+
locale,
|
|
311
|
+
setLocale2,
|
|
312
|
+
status,
|
|
313
|
+
translations,
|
|
314
|
+
error,
|
|
315
|
+
refetch
|
|
316
|
+
]);
|
|
317
|
+
return /* @__PURE__ */ jsx(DocyrusI18nContext.Provider, { value, children });
|
|
318
|
+
}
|
|
319
|
+
function useDocyrusI18n() {
|
|
320
|
+
const context = useContext(DocyrusI18nContext);
|
|
321
|
+
if (!context) {
|
|
322
|
+
throw new Error(
|
|
323
|
+
"useDocyrusI18n() must be used within a <DocyrusI18nProvider>. Wrap your app with <DocyrusI18nProvider> to provide i18n context."
|
|
324
|
+
);
|
|
325
|
+
}
|
|
326
|
+
return context;
|
|
327
|
+
}
|
|
328
|
+
function useTranslation() {
|
|
329
|
+
const context = useContext(DocyrusI18nContext);
|
|
330
|
+
if (!context) {
|
|
331
|
+
throw new Error(
|
|
332
|
+
"useTranslation() must be used within a <DocyrusI18nProvider>. Wrap your app with <DocyrusI18nProvider> to provide i18n context."
|
|
333
|
+
);
|
|
334
|
+
}
|
|
335
|
+
return { t: context.t, isLoading: context.isLoading };
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
export { DocyrusI18nContext, DocyrusI18nProvider, I18nManager, getLocale, interpolate, setLocale, useDocyrusI18n, useTranslation };
|
|
339
|
+
//# sourceMappingURL=index.js.map
|
|
340
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/core/interpolation.ts","../src/core/locale-storage.ts","../src/core/i18n-manager.ts","../src/components/docyrus-i18n-provider.tsx","../src/hooks/use-i18n.ts","../src/hooks/use-translation.ts"],"names":["setLocale","useContext"],"mappings":";;;;;;AAeO,SAAS,WAAA,CACd,UACA,MAAA,EACQ;AACR,EAAA,IAAI,CAAC,QAAQ,OAAO,QAAA;AAGpB,EAAA,OAAO,QAAA,CAAS,OAAA;AAAA,IACd,0BAAA;AAAA,IACA,CAAC,KAAA,EAAO,cAAA,EAAoC,cAAA,KAAuC;AACjF,MAAA,MAAM,MAAM,cAAA,IAAkB,cAAA;AAE9B,MAAA,IAAI,GAAA,KAAQ,QAAW,OAAO,KAAA;AAE9B,MAAA,MAAM,KAAA,GAAQ,OAAO,GAAG,CAAA;AAExB,MAAA,OAAO,KAAA,KAAU,MAAA,GAAY,MAAA,CAAO,KAAK,CAAA,GAAI,KAAA;AAAA,IAC/C;AAAA,GACF;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AS,cAAA,GAAiB;AAC/B,EAAA,MAAM,OAAA,GAAUC,WAAW,kBAAkB,CAAA;AAE7C,EAAA,IAAI,CAAC,OAAA,EAAS;AACZ,IAAA,MAAM,IAAI,KAAA;AAAA,MACR;AAAA,KAEF;AAAA,EACF;AAEA,EAAA,OAAO,EAAE,CAAA,EAAG,OAAA,CAAQ,CAAA,EAAG,SAAA,EAAW,QAAQ,SAAA,EAAU;AACtD","file":"index.js","sourcesContent":["/**\n * Interpolate placeholders in a translation string.\n *\n * Supports three formats (checked in order):\n * 1. {{variable}} — double-brace (static translations convention)\n * 2. {variable} — single-brace named (API convention: \"Talk to {name} AI\")\n * 3. {0}, {1} — single-brace positional (API convention: \"Add New {0}\")\n *\n * Positional placeholders use numeric keys: params = { '0': 'User' }\n *\n * Examples:\n * interpolate('Hello, {{name}}!', { name: 'Ali' }) → 'Hello, Ali!'\n * interpolate('Talk to {name} AI', { name: 'Docyrus' }) → 'Talk to Docyrus AI'\n * interpolate('Add New {0}', { '0': 'User' }) → 'Add New User'\n */\nexport function interpolate(\n template: string,\n params?: Record<string, string | number>\n): string {\n if (!params) return template;\n\n // Match both {{key}} and {key} — double-brace first, then single-brace\n return template.replace(\n /\\{\\{(\\w+)\\}\\}|\\{(\\w+)\\}/g,\n (match, doubleBraceKey: string | undefined, singleBraceKey: string | undefined) => {\n const key = doubleBraceKey ?? singleBraceKey;\n\n if (key === undefined) return match;\n\n const value = params[key];\n\n return value !== undefined ? String(value) : match;\n }\n );\n}\n","const DEFAULT_MAX_AGE = 365 * 24 * 60 * 60; // 1 year in seconds\n\n/**\n * Read the locale from a cookie. SSR-safe.\n * Returns null if the cookie is not set or not in a browser environment.\n */\nexport function getLocale(cookieKey: string): string | null {\n if (typeof document === 'undefined') return null;\n\n const match = document.cookie.match(new RegExp(`(?:^|;\\\\s*)${escapeRegex(cookieKey)}=([^;]*)`));\n\n return match ? decodeURIComponent(match[1]) : null;\n}\n\n/**\n * Write the locale to a cookie. SSR-safe (no-op on server).\n */\nexport function setLocale(cookieKey: string, locale: string): void {\n if (typeof document === 'undefined') return;\n\n document.cookie = `${cookieKey}=${encodeURIComponent(locale)};path=/;max-age=${DEFAULT_MAX_AGE};SameSite=Lax`;\n}\n\nfunction escapeRegex(str: string): string {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n","import { type RestApiClient } from '@docyrus/api-client';\n\nimport {\n type DocyrusI18nConfig,\n type FallbackStrategy,\n type I18nStatus,\n type TranslationDictionary,\n type TranslationsResponse\n} from '../types';\n\nimport { interpolate } from './interpolation';\nimport { getLocale, setLocale as writeLocaleCookie } from './locale-storage';\n\nexport type I18nStateListener = (state: {\n status: I18nStatus;\n locale: string | null;\n translations: TranslationDictionary;\n error: Error | null;\n}) => void;\n\n/**\n * Framework-agnostic translation engine.\n *\n * Manages locale persistence (cookie), translation fetching (API + static merge),\n * and provides the `t()` function for translation lookup with interpolation.\n *\n * Pattern follows AuthManager from @docyrus/app-auth-ui.\n */\nexport class I18nManager {\n private status: I18nStatus = 'loading';\n private locale: string | null;\n private translations: TranslationDictionary = {};\n private apiTranslations: TranslationDictionary = {};\n private error: Error | null = null;\n private listeners: Set<I18nStateListener> = new Set();\n private abortController: AbortController | null = null;\n private client: RestApiClient | null;\n private getAccessToken: (() => Promise<string | null> | string | null) | undefined;\n private apiUrl: string | undefined;\n private translationsEndpoint: string;\n private staticTranslations: TranslationDictionary;\n private cookieKey: string;\n private mergeStrategy: 'api-first' | 'static-first';\n private fallback: FallbackStrategy;\n private disableApiFetch: boolean;\n private userLanguageEndpoint: string | false;\n constructor(config: DocyrusI18nConfig) {\n this.client = config.client ?? null;\n this.getAccessToken = config.getAccessToken;\n this.apiUrl = config.apiUrl;\n this.translationsEndpoint = config.translationsEndpoint ?? 'tenant/translations';\n this.staticTranslations = config.staticTranslations ?? {};\n this.cookieKey = config.cookieKey ?? 'docyrus-locale';\n this.mergeStrategy = config.mergeStrategy ?? 'api-first';\n this.fallback = config.fallback ?? 'key';\n this.disableApiFetch = config.disableApiFetch ?? false;\n this.userLanguageEndpoint = config.userLanguageEndpoint ?? 'users/me';\n\n // Read locale from cookie (null if not set — API resolves from user profile)\n this.locale = getLocale(this.cookieKey);\n }\n getStatus(): I18nStatus {\n return this.status;\n }\n getLocale(): string | null {\n return this.locale;\n }\n getTranslations(): TranslationDictionary {\n return this.translations;\n }\n getError(): Error | null {\n return this.error;\n }\n subscribe(listener: I18nStateListener): () => void {\n this.listeners.add(listener);\n\n return () => this.listeners.delete(listener);\n }\n private notify(): void {\n for (const listener of this.listeners) {\n listener({\n status: this.status,\n locale: this.locale,\n translations: this.translations,\n error: this.error\n });\n }\n }\n /**\n * Initialize the manager.\n * 1. Apply static translations immediately (no loading flash).\n * 2. Fetch from API if enabled and auth is available.\n */\n async initialize(): Promise<void> {\n // Apply static translations immediately\n if (Object.keys(this.staticTranslations).length > 0) {\n this.translations = { ...this.staticTranslations };\n this.status = 'ready';\n this.notify();\n }\n\n // Fetch from API\n if (!this.disableApiFetch && (this.client || this.getAccessToken)) {\n await this.fetchTranslations();\n } else if (this.status !== 'ready') {\n // No static translations and no API fetch — mark ready with empty translations\n this.status = 'ready';\n this.notify();\n }\n }\n /**\n * Fetch translations from the API.\n * Uses RestApiClient.get() if client is available, otherwise raw fetch with getAccessToken.\n */\n async fetchTranslations(): Promise<void> {\n // Abort any in-flight request\n this.abortController?.abort();\n this.abortController = new AbortController();\n\n try {\n let apiData: TranslationsResponse;\n\n if (this.client) {\n apiData = await this.client.get<TranslationsResponse>(\n this.translationsEndpoint\n );\n } else if (this.getAccessToken && this.apiUrl) {\n const token = await this.getAccessToken();\n\n if (!token) {\n throw new Error('getAccessToken returned null — cannot fetch translations');\n }\n\n const url = `${this.apiUrl.replace(/\\/$/, '')}/${this.translationsEndpoint}`;\n const res = await fetch(url, {\n headers: { Authorization: `Bearer ${token}` },\n signal: this.abortController.signal\n });\n\n if (!res.ok) {\n throw new Error(`Translation fetch failed: ${res.status} ${res.statusText}`);\n }\n\n apiData = await res.json() as TranslationsResponse;\n } else {\n // No auth available yet — skip silently\n return;\n }\n\n this.apiTranslations = apiData.data;\n this.mergeTranslations();\n this.error = null;\n this.status = 'ready';\n this.notify();\n } catch (err) {\n if ((err as Error).name === 'AbortError') return;\n\n this.error = err instanceof Error ? err : new Error(String(err));\n\n // If we already have static translations, stay 'ready' with error\n if (Object.keys(this.translations).length > 0) {\n this.notify();\n } else {\n this.status = 'error';\n this.notify();\n }\n }\n }\n /**\n * Translate a key with optional interpolation.\n * Falls back based on the configured strategy.\n */\n t(key: string, params?: Record<string, string | number>): string {\n const value = this.translations[key];\n\n if (value !== undefined) {\n return interpolate(value, params);\n }\n\n // Fallback\n if (this.fallback === 'key') return key;\n if (this.fallback === 'empty') return '';\n\n return this.fallback(key);\n }\n /**\n * Change the active locale.\n * Writes to cookie, persists to API (PATCH users/me), and triggers translation refetch.\n */\n async setLocale(locale: string): Promise<void> {\n if (locale === this.locale) return;\n\n this.locale = locale;\n writeLocaleCookie(this.cookieKey, locale);\n this.notify();\n\n // Persist language preference to API + refetch translations in parallel\n const promises: Promise<void>[] = [];\n\n if (this.userLanguageEndpoint !== false && (this.client || this.getAccessToken)) {\n promises.push(this.persistUserLanguage(locale));\n }\n\n if (!this.disableApiFetch && (this.client || this.getAccessToken)) {\n promises.push(this.fetchTranslations());\n }\n\n await Promise.all(promises);\n }\n /**\n * Persist user language preference to API.\n * PATCH {userLanguageEndpoint} { language: locale }\n */\n private async persistUserLanguage(locale: string): Promise<void> {\n if (this.userLanguageEndpoint === false) return;\n\n try {\n if (this.client) {\n await this.client.patch(this.userLanguageEndpoint, { language: locale });\n } else if (this.getAccessToken && this.apiUrl) {\n const token = await this.getAccessToken();\n\n if (!token) return;\n\n const url = `${this.apiUrl.replace(/\\/$/, '')}/${this.userLanguageEndpoint}`;\n\n await fetch(url, {\n method: 'PATCH',\n headers: {\n Authorization: `Bearer ${token}`,\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify({ language: locale })\n });\n }\n } catch {\n // Language persist is best-effort — don't block locale switch on failure\n }\n }\n /**\n * Update config at runtime.\n * Useful when client transitions from null → RestApiClient (auth loading complete).\n */\n updateConfig(updates: Partial<Pick<DocyrusI18nConfig, 'client' | 'staticTranslations'>>): void {\n let shouldFetch = false;\n\n if (updates.client !== undefined && updates.client !== this.client) {\n const hadNoClient = !this.client;\n\n this.client = updates.client;\n\n // Client became available — fetch translations\n if (hadNoClient && this.client && !this.disableApiFetch) {\n shouldFetch = true;\n }\n }\n\n if (updates.staticTranslations !== undefined) {\n this.staticTranslations = updates.staticTranslations;\n this.mergeTranslations();\n this.notify();\n }\n\n if (shouldFetch) {\n this.fetchTranslations();\n }\n }\n /** Cleanup: abort in-flight requests + clear listeners. */\n destroy(): void {\n this.abortController?.abort();\n this.listeners.clear();\n }\n private mergeTranslations(): void {\n if (this.mergeStrategy === 'api-first') {\n this.translations = { ...this.staticTranslations, ...this.apiTranslations };\n } else {\n this.translations = { ...this.apiTranslations, ...this.staticTranslations };\n }\n }\n}\n","'use client';\n\nimport {\n createContext,\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n type ReactNode\n} from 'react';\n\nimport { type RestApiClient } from '@docyrus/api-client';\n\nimport {\n type DocyrusI18nConfig,\n type DocyrusI18nContextValue,\n type I18nStatus,\n type TranslationDictionary\n} from '../types';\n\nimport { I18nManager } from '../core/i18n-manager';\n\nexport const DocyrusI18nContext = createContext<DocyrusI18nContextValue | null>(null);\n\nexport interface DocyrusI18nProviderProps extends DocyrusI18nConfig {\n children: ReactNode;\n}\n\nexport function DocyrusI18nProvider({\n children,\n ...config\n}: DocyrusI18nProviderProps) {\n const [status, setStatus] = useState<I18nStatus>(\n config.staticTranslations && Object.keys(config.staticTranslations).length > 0 ? 'ready' : 'loading'\n );\n const [locale, setLocaleState] = useState<string | null>(null);\n const [translations, setTranslations] = useState<TranslationDictionary>(\n config.staticTranslations ?? {}\n );\n const [error, setError] = useState<Error | null>(null);\n const managerRef = useRef<I18nManager | null>(null);\n\n useEffect(() => {\n const manager = new I18nManager(config);\n\n managerRef.current = manager;\n setLocaleState(manager.getLocale());\n\n const unsubscribe = manager.subscribe((state) => {\n setStatus(state.status);\n setLocaleState(state.locale);\n setTranslations(state.translations);\n setError(state.error);\n });\n\n manager.initialize();\n\n return () => {\n unsubscribe();\n manager.destroy();\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n // React to client prop changes (null → RestApiClient transition)\n const clientRef = useRef<RestApiClient | null | undefined>(config.client);\n\n useEffect(() => {\n if (config.client !== clientRef.current) {\n clientRef.current = config.client;\n managerRef.current?.updateConfig({ client: config.client });\n }\n }, [config.client]);\n\n const setLocale = useCallback((newLocale: string) => {\n managerRef.current?.setLocale(newLocale);\n }, []);\n\n const refetch = useCallback(async () => {\n await managerRef.current?.fetchTranslations();\n }, []);\n\n const t = useCallback(\n (key: string, params?: Record<string, string | number>) => {\n return managerRef.current?.t(key, params) ?? key;\n },\n // Re-create t when translations change so consumers re-render\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [translations]\n );\n\n const value = useMemo<DocyrusI18nContextValue>(() => ({\n t,\n locale,\n setLocale,\n status,\n isLoading: status === 'loading',\n translations,\n error,\n refetch\n }), [\n t,\n locale,\n setLocale,\n status,\n translations,\n error,\n refetch\n ]);\n\n return (\n <DocyrusI18nContext.Provider value={value}>\n {children}\n </DocyrusI18nContext.Provider>\n );\n}\n","import { useContext } from 'react';\n\nimport { type DocyrusI18nContextValue } from '../types';\n\nimport { DocyrusI18nContext } from '../components/docyrus-i18n-provider';\n\n/**\n * Access the full Docyrus i18n context.\n * Must be used within a `<DocyrusI18nProvider>`.\n *\n * Returns: { t, locale, setLocale, status, isLoading, translations, error, refetch }\n */\nexport function useDocyrusI18n(): DocyrusI18nContextValue {\n const context = useContext(DocyrusI18nContext);\n\n if (!context) {\n throw new Error(\n 'useDocyrusI18n() must be used within a <DocyrusI18nProvider>. '\n + 'Wrap your app with <DocyrusI18nProvider> to provide i18n context.'\n );\n }\n\n return context;\n}\n","import { useContext } from 'react';\n\nimport { DocyrusI18nContext } from '../components/docyrus-i18n-provider';\n\n/**\n * Lightweight hook for translation only.\n * Returns just `t` and `isLoading` — use `useDocyrusI18n()` for full context.\n *\n * Must be used within a `<DocyrusI18nProvider>`.\n */\nexport function useTranslation() {\n const context = useContext(DocyrusI18nContext);\n\n if (!context) {\n throw new Error(\n 'useTranslation() must be used within a <DocyrusI18nProvider>. '\n + 'Wrap your app with <DocyrusI18nProvider> to provide i18n context.'\n );\n }\n\n return { t: context.t, isLoading: context.isLoading };\n}\n"]}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { RestApiClient } from '@docyrus/api-client';
|
|
2
|
+
|
|
3
|
+
type I18nStatus = 'loading' | 'ready' | 'error';
|
|
4
|
+
type TranslationDictionary = Record<string, string>;
|
|
5
|
+
type FallbackStrategy = 'key' | 'empty' | ((key: string) => string);
|
|
6
|
+
interface TranslationsResponse {
|
|
7
|
+
success: boolean;
|
|
8
|
+
data: TranslationDictionary;
|
|
9
|
+
}
|
|
10
|
+
interface DocyrusI18nConfig {
|
|
11
|
+
/** Pre-configured RestApiClient with auto-refresh tokens. Primary auth method. */
|
|
12
|
+
client?: RestApiClient | null;
|
|
13
|
+
/** Alternative auth: callback returning access token string. Used for SSR or custom setups. */
|
|
14
|
+
getAccessToken?: () => Promise<string | null> | string | null;
|
|
15
|
+
/** API base URL. Required when using getAccessToken (not needed with client). */
|
|
16
|
+
apiUrl?: string;
|
|
17
|
+
/** API endpoint path for translations. Default: 'tenant/translations' */
|
|
18
|
+
translationsEndpoint?: string;
|
|
19
|
+
/** Pre-loaded translations (e.g. from SSR or static JSON). Available immediately, no loading state. */
|
|
20
|
+
staticTranslations?: TranslationDictionary;
|
|
21
|
+
/** Cookie key for locale persistence. Default: 'docyrus-locale' */
|
|
22
|
+
cookieKey?: string;
|
|
23
|
+
/** How to merge static and API translations. Default: 'api-first' */
|
|
24
|
+
mergeStrategy?: 'api-first' | 'static-first';
|
|
25
|
+
/** What to return when a key is not found. Default: 'key' */
|
|
26
|
+
fallback?: FallbackStrategy;
|
|
27
|
+
/** Skip API fetch entirely. Use only staticTranslations. Default: false */
|
|
28
|
+
disableApiFetch?: boolean;
|
|
29
|
+
/**
|
|
30
|
+
* API endpoint to persist user language preference via PATCH.
|
|
31
|
+
* Set to false to disable. Default: 'users/me'
|
|
32
|
+
* Sends: PATCH {endpoint} { language: locale }
|
|
33
|
+
*/
|
|
34
|
+
userLanguageEndpoint?: string | false;
|
|
35
|
+
}
|
|
36
|
+
interface DocyrusI18nContextValue {
|
|
37
|
+
/** Translate a key with optional interpolation params. */
|
|
38
|
+
t: (key: string, params?: Record<string, string | number>) => string;
|
|
39
|
+
/** Current active locale (null until first setLocale or cookie read). */
|
|
40
|
+
locale: string | null;
|
|
41
|
+
/** Change locale — writes cookie + refetches translations. */
|
|
42
|
+
setLocale: (locale: string) => void;
|
|
43
|
+
/** Current status of the i18n system. */
|
|
44
|
+
status: I18nStatus;
|
|
45
|
+
/** Convenience: true when status is 'loading'. */
|
|
46
|
+
isLoading: boolean;
|
|
47
|
+
/** Current merged translations dictionary. */
|
|
48
|
+
translations: TranslationDictionary;
|
|
49
|
+
/** Last error, if any. */
|
|
50
|
+
error: Error | null;
|
|
51
|
+
/** Manually refetch translations from the API. */
|
|
52
|
+
refetch: () => Promise<void>;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export type { DocyrusI18nConfig as D, FallbackStrategy as F, I18nStatus as I, TranslationDictionary as T, DocyrusI18nContextValue as a, TranslationsResponse as b };
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import * as vue from 'vue';
|
|
2
|
+
import { PropType } from 'vue';
|
|
3
|
+
import { RestApiClient } from '@docyrus/api-client';
|
|
4
|
+
import { I as I18nStatus, T as TranslationDictionary, F as FallbackStrategy } from '../types-DQtgewNG.js';
|
|
5
|
+
export { D as DocyrusI18nConfig } from '../types-DQtgewNG.js';
|
|
6
|
+
|
|
7
|
+
interface DocyrusI18nState {
|
|
8
|
+
status: I18nStatus;
|
|
9
|
+
locale: string | null;
|
|
10
|
+
translations: TranslationDictionary;
|
|
11
|
+
error: Error | null;
|
|
12
|
+
isLoading: boolean;
|
|
13
|
+
t: (key: string, params?: Record<string, string | number>) => string;
|
|
14
|
+
setLocale: (locale: string) => void;
|
|
15
|
+
refetch: () => Promise<void>;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Vue composable to access full Docyrus i18n state.
|
|
19
|
+
* Must be used within a `<DocyrusI18nProvider>`.
|
|
20
|
+
*
|
|
21
|
+
* Returns: { t, locale, setLocale, status, isLoading, translations, error, refetch }
|
|
22
|
+
*/
|
|
23
|
+
declare function useDocyrusI18n(): DocyrusI18nState;
|
|
24
|
+
/**
|
|
25
|
+
* Lightweight composable for translation only.
|
|
26
|
+
* Returns just `t` and `isLoading`.
|
|
27
|
+
*/
|
|
28
|
+
declare function useTranslation(): {
|
|
29
|
+
t: vue.ComputedRef<(key: string, params?: Record<string, string | number>) => string>;
|
|
30
|
+
isLoading: vue.ComputedRef<boolean>;
|
|
31
|
+
};
|
|
32
|
+
/**
|
|
33
|
+
* Vue provider component that wraps your app with Docyrus i18n context.
|
|
34
|
+
*
|
|
35
|
+
* Usage:
|
|
36
|
+
* ```vue
|
|
37
|
+
* <template>
|
|
38
|
+
* <DocyrusI18nProvider :client="client">
|
|
39
|
+
* <App />
|
|
40
|
+
* </DocyrusI18nProvider>
|
|
41
|
+
* </template>
|
|
42
|
+
*
|
|
43
|
+
* <script setup>
|
|
44
|
+
* import { DocyrusI18nProvider } from '@docyrus/i18n/vue';
|
|
45
|
+
* </script>
|
|
46
|
+
* ```
|
|
47
|
+
*/
|
|
48
|
+
declare const DocyrusI18nProvider: vue.DefineComponent<vue.ExtractPropTypes<{
|
|
49
|
+
client: {
|
|
50
|
+
type: PropType<RestApiClient | null>;
|
|
51
|
+
default: null;
|
|
52
|
+
};
|
|
53
|
+
getAccessToken: {
|
|
54
|
+
type: PropType<() => Promise<string | null> | string | null>;
|
|
55
|
+
default: undefined;
|
|
56
|
+
};
|
|
57
|
+
apiUrl: {
|
|
58
|
+
type: StringConstructor;
|
|
59
|
+
default: undefined;
|
|
60
|
+
};
|
|
61
|
+
translationsEndpoint: {
|
|
62
|
+
type: StringConstructor;
|
|
63
|
+
default: undefined;
|
|
64
|
+
};
|
|
65
|
+
staticTranslations: {
|
|
66
|
+
type: PropType<TranslationDictionary>;
|
|
67
|
+
default: undefined;
|
|
68
|
+
};
|
|
69
|
+
cookieKey: {
|
|
70
|
+
type: StringConstructor;
|
|
71
|
+
default: undefined;
|
|
72
|
+
};
|
|
73
|
+
mergeStrategy: {
|
|
74
|
+
type: PropType<"api-first" | "static-first">;
|
|
75
|
+
default: undefined;
|
|
76
|
+
};
|
|
77
|
+
fallback: {
|
|
78
|
+
type: PropType<FallbackStrategy>;
|
|
79
|
+
default: undefined;
|
|
80
|
+
};
|
|
81
|
+
disableApiFetch: {
|
|
82
|
+
type: BooleanConstructor;
|
|
83
|
+
default: undefined;
|
|
84
|
+
};
|
|
85
|
+
}>, () => vue.VNode<vue.RendererNode, vue.RendererElement, {
|
|
86
|
+
[key: string]: any;
|
|
87
|
+
}>[] | undefined, {}, {}, {}, vue.ComponentOptionsMixin, vue.ComponentOptionsMixin, {}, string, vue.PublicProps, Readonly<vue.ExtractPropTypes<{
|
|
88
|
+
client: {
|
|
89
|
+
type: PropType<RestApiClient | null>;
|
|
90
|
+
default: null;
|
|
91
|
+
};
|
|
92
|
+
getAccessToken: {
|
|
93
|
+
type: PropType<() => Promise<string | null> | string | null>;
|
|
94
|
+
default: undefined;
|
|
95
|
+
};
|
|
96
|
+
apiUrl: {
|
|
97
|
+
type: StringConstructor;
|
|
98
|
+
default: undefined;
|
|
99
|
+
};
|
|
100
|
+
translationsEndpoint: {
|
|
101
|
+
type: StringConstructor;
|
|
102
|
+
default: undefined;
|
|
103
|
+
};
|
|
104
|
+
staticTranslations: {
|
|
105
|
+
type: PropType<TranslationDictionary>;
|
|
106
|
+
default: undefined;
|
|
107
|
+
};
|
|
108
|
+
cookieKey: {
|
|
109
|
+
type: StringConstructor;
|
|
110
|
+
default: undefined;
|
|
111
|
+
};
|
|
112
|
+
mergeStrategy: {
|
|
113
|
+
type: PropType<"api-first" | "static-first">;
|
|
114
|
+
default: undefined;
|
|
115
|
+
};
|
|
116
|
+
fallback: {
|
|
117
|
+
type: PropType<FallbackStrategy>;
|
|
118
|
+
default: undefined;
|
|
119
|
+
};
|
|
120
|
+
disableApiFetch: {
|
|
121
|
+
type: BooleanConstructor;
|
|
122
|
+
default: undefined;
|
|
123
|
+
};
|
|
124
|
+
}>> & Readonly<{}>, {
|
|
125
|
+
client: RestApiClient | null;
|
|
126
|
+
getAccessToken: () => Promise<string | null> | string | null;
|
|
127
|
+
apiUrl: string;
|
|
128
|
+
translationsEndpoint: string;
|
|
129
|
+
staticTranslations: TranslationDictionary;
|
|
130
|
+
cookieKey: string;
|
|
131
|
+
mergeStrategy: "api-first" | "static-first";
|
|
132
|
+
fallback: FallbackStrategy;
|
|
133
|
+
disableApiFetch: boolean;
|
|
134
|
+
}, {}, {}, {}, string, vue.ComponentProvideOptions, true, {}, any>;
|
|
135
|
+
|
|
136
|
+
export { DocyrusI18nProvider, type DocyrusI18nState, FallbackStrategy, I18nStatus, TranslationDictionary, useDocyrusI18n, useTranslation };
|