1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
//! Dynamic internationalization (i18n) and diagnostic localization engine powered by Project Fluent.
//!
//! Provides a thread-safe message formatting environment, multi-tier runtime locale resolution,
//! task-isolated execution contexts via Tokio Task-Local storage, and an extensible registry
//! for external downstream crate translation bundles.
//!
//! ### Multi-Tier Locale Resolution Hierarchy
//!
//! When resolving the active translation, the engine queries four priority tiers in descending order:
//!
//! ```text
//! 1. Tokio Task-Local Context (TASK_LOCALE) <-- Isolated per asynchronous task (e.g. per-user bot requests)
//! │
//! ▼ (if absent or empty)
//! 2. Global Process Override (GLOBAL_LOCALE) <-- Set via set_global_locale("ru") (CLI / tests)
//! │
//! ▼ (if absent or empty)
//! 3. Host OS Regional Settings (sys-locale) <-- Discovered from operating system environment
//! │
//! ▼ (if unsupported)
//! 4. Canonical Fallback Locale ("en") <-- Guaranteed to contain 100% of all keys
//! ```
//!
//! ### Unicode BiDi Isolation Suppression
//!
//! By default, Project Fluent injects invisible Unicode First Strong directional isolation
//! characters (`\u{2068}` and `\u{2069}`) around interpolated terms. While helpful in mixed-script
//! desktop GUIs, these markers corrupt Markdown syntax, break HTML tags, and invalidate URL paths.
//! All bundles generated by this engine explicitly disable directional isolation via
//! [`FluentBundle::set_use_isolating(false)`](https://docs.rs/fluent/latest/fluent/bundle/struct.FluentBundle.html#method.set_use_isolating).
//!
//! ### Quick Example
//!
//! ```rust
//! use moonclient::{set_global_locale, tr};
//!
//! // 1. Format in default locale (en)
//! let msg_en = tr!("api-error", "code" => 404, "message" => "Not Found");
//! println!("English: {}", msg_en);
//!
//! // 2. Switch global locale to Russian
//! set_global_locale("ru");
//! let msg_ru = tr!("api-error", "code" => 404, "message" => "Не найдено");
//! println!("Russian: {}", msg_ru);
//! ```
pub use FluentArgs;
use FluentResource;
use FluentBundle;
use HashMap;
use ;
use LanguageIdentifier;
/// Primary default language code (`"en"`) applied when requested locales are unavailable.
const DEFAULT_LOCALE: &str = "en";
/// Canonical fallback language code (`"en"`) guaranteed to contain an exhaustive set of all translation keys.
const FALLBACK_LOCALE: &str = "en";
// Tokio task-local storage macro. Allows isolating language context
// across independent asynchronous execution tasks (e.g., individual user locales in bots or web requests).
task_local!
/// Global process-wide language context for CLI applications, monoliths, and test suites.
static GLOBAL_LOCALE: = new;
/// Type alias for a thread-safe concurrent Fluent bundle with memoization support.
type ConcurrentBundle = ;
/// Global lazy-initialized storage of compiled language dictionaries protected by an [`std::sync::RwLock`].
///
/// Compiles the embedded core network translations (`en-US` and `ru-RU`) upon first access.
static BUNDLES: = new;
/// Internal helper function to instantiate an isolated, thread-safe Fluent bundle.
///
/// # Implementation Details
///
/// 1. Parses raw FTL source text into a [`FluentResource`](https://docs.rs/fluent/latest/fluent/struct.FluentResource.html).
/// 2. Parses the BCP-47 language tag into a [`LanguageIdentifier`](https://docs.rs/unic-langid/latest/unic_langid/struct.LanguageIdentifier.html).
/// 3. Disables bidirectional text isolation markers via `set_use_isolating(false)` to prevent string corruption.
/// 4. Registers the resource into the bundle.
///
/// # Arguments
///
/// * `lang` ([`&str`]) — BCP-47 language tag (e.g. `"en-US"`, `"ru-RU"`).
/// * `source` ([`&str`]) — Raw FTL resource syntax text.
///
/// # Returns
///
/// Returns a compiled [`ConcurrentBundle`] ready for message formatting.
/// Registers an external FTL resource bundle from a dependent downstream crate.
///
/// Allows external libraries (such as `shikimori_api` or domain plugins) to inject
/// their own localization dictionaries into the shared engine pool without exposing
/// direct dependencies on the underlying Fluent crates.
///
/// If the target language already exists in memory, new keys will extend the bundle,
/// overriding duplicate keys. If absent, a new bundle is dynamically allocated.
///
/// # Arguments
///
/// * `lang` ([`&str`]) — BCP-47 language identifier tag (e.g. `"en"`, `"ru"`, `"ja-JP"`).
/// * `source` (`&'static str`) — Static source string containing Project Fluent dictionary definitions.
///
/// # Example
///
/// ```rust
/// use moonclient::{register_resource, set_global_locale, tr};
///
/// // Register custom translations from an external domain crate
/// register_resource("en", "welcome-msg = Welcome to our service, {$name}!");
/// register_resource("ru", "welcome-msg = Добро пожаловать, {$name}!");
///
/// set_global_locale("ru");
/// let greeting = tr!("welcome-msg", "name" => "Dina");
/// assert_eq!(greeting, "Добро пожаловать, Dina!");
/// ```
/// Sets the process-wide global default locale override.
///
/// Overrides host OS regional settings for monolithic runtimes, CLI applications,
/// and automated integration test suites where task-local isolation is unnecessary.
///
/// # Arguments
///
/// * `locale` ([`&str`]) — Target language code (e.g. `"en"`, `"ru"`).
///
/// # Example
///
/// ```rust
/// use moonclient::set_global_locale;
///
/// set_global_locale("ru");
/// println!("Global locale switched to Russian");
/// ```
/// Normalizes an incoming raw language tag string to the core engine standard.
///
/// Inspects language tag prefixes and maps them to primary two-letter forms,
/// falling back to `DEFAULT_LOCALE` (`"en"`) if no match is found.
///
/// # Arguments
///
/// * `code` ([`Option<&str>`]) — Optional raw language code string (e.g. `Some("ru-RU")`, `Some("en_US")`).
///
/// # Returns
///
/// Normalized two-letter lowercase language identifier string (`"en"` or `"ru"`).
///
/// # Example
///
/// ```rust
/// use moonclient::i18n::normalize_language_code;
///
/// assert_eq!(normalize_language_code(Some("ru-RU")), "ru");
/// assert_eq!(normalize_language_code(Some("en-US")), "en");
/// assert_eq!(normalize_language_code(None), "en");
/// ```
/// Resolves the currently active locale code based on the priority hierarchy.
///
/// # Implementation Details
///
/// 1. Inspects the active [`TASK_LOCALE`] Tokio context. If set and non-empty, returns it immediately.
/// 2. Inspects [`GLOBAL_LOCALE`]. If configured, returns the global override string.
/// 3. Queries host operating system settings via [`sys_locale::get_locale`](https://docs.rs/sys-locale/latest/sys_locale/fn.get_locale.html).
/// 4. Defaults to [`DEFAULT_LOCALE`] (`"en"`).
///
/// # Returns
///
/// A normalized two-letter language code string representing the current execution context.
/// Retrieves, interpolates, and formats a localized message pattern from a bundle.
///
/// # Implementation Details
///
/// Looks up `key` in the bundle. If present, interpolates arguments via
/// [`FluentBundle::format_pattern`](https://docs.rs/fluent/latest/fluent/bundle/struct.FluentBundle.html#method.format_pattern).
/// Replaces escaped `\n` sequences with real newline characters only when detected,
/// minimizing redundant heap allocations.
///
/// # Arguments
///
/// * `bundle` (`&ConcurrentBundle`) — Reference to the target compiled Fluent bundle.
/// * `key` ([`&str`]) — Unique message identifier defined in the FTL dictionary.
/// * `args` ([`Option<&FluentArgs>`]) — Optional variable arguments for template interpolation.
///
/// # Returns
///
/// Returns `Some(String)` containing the formatted text, or `None` if `key` does not exist in `bundle`.
/// Translates and formats a localized message by its dictionary key.
///
/// Resolves the active locale through the multi-tier hierarchy, locates the target message,
/// and interpolates variables. If the active locale lacks the requested key, it automatically
/// falls back to the canonical `FALLBACK_LOCALE` bundle.
///
/// If the key is missing across all registered dictionaries, returns the raw key wrapped
/// in brackets (e.g. `"[missing-key]"`).
///
/// # Arguments
///
/// * `key` ([`&str`]) — Unique message identifier defined in FTL dictionaries.
/// * `args` ([`Option<&FluentArgs>`]) — Optional collection of named interpolation arguments.
///
/// # Returns
///
/// Formatted, localized string ready for logging or display.
///
/// # Example
///
/// ```rust
/// use moonclient::i18n::translate;
///
/// let message = translate("expect-invalid-base-url", None);
/// println!("Resolved message: {}", message);
/// ```
/// Primary declarative macro for translating and interpolating localized messages.
///
/// Provides a concise syntax for formatting static translation keys as well as
/// templates requiring dynamic, named arguments implementing [`std::fmt::Display`].
///
/// # Syntax
///
/// * `tr!("key")` — Static key lookup without arguments.
/// * `tr!("key", "param1" => val1, "param2" => val2)` — Interpolated message with dynamic named parameters.
///
/// # Examples
///
/// ### Static Key Translation
/// ```rust
/// use moonclient::tr;
///
/// let err_msg = tr!("expect-invalid-base-url");
/// println!("Static message: {}", err_msg);
/// ```
///
/// ### Dynamic Named Argument Interpolation
/// ```rust
/// use moonclient::tr;
///
/// let error_detail = "Connection timed out";
/// let count = 3_u32;
///
/// let log_entry = tr!("err-network", "error" => error_detail, "retries" => count);
/// println!("Interpolated log entry: {}", log_entry);
/// ```