@rivinia/i18n 0.3.3 → 0.5.0

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.
@@ -1,5 +1,5 @@
1
1
  import * as i0 from "@angular/core";
2
- import { EnvironmentProviders, InjectionToken } from "@angular/core";
2
+ import { EnvironmentProviders, Signal } from "@angular/core";
3
3
  /** Text rendering direction. */
4
4
  type Direction = 'ltr' | 'rtl';
5
5
  /**
@@ -22,12 +22,18 @@ interface Language<T extends string = string> {
22
22
  type Translation<T extends string> = Record<T, string>;
23
23
  /** Persistence backend. SSR-safe: everything degrades to no-op off-browser. */
24
24
  type StorageStrategy = 'local' | 'session' | 'none' | 'cookie';
25
- /** Interpolation + ICU params (`{count}`, `{gender}`). */
26
- type TranslateParams = Record<string, string | number | boolean>;
25
+ /**
26
+ * Interpolation + ICU params (`{count}`, `{gender}`, `{day, date}`).
27
+ * `Date` values are consumed by `{d, date[, style]}`; a plain `{name}`
28
+ * renders them with `String(value)`.
29
+ */
30
+ type TranslateParams = Record<string, string | number | boolean | Date>;
31
+ /** @experimental The view-transition integration may change before 1.0. */
27
32
  interface ViewTransitionInfo {
28
33
  readonly language: string;
29
34
  readonly direction: Direction;
30
35
  }
36
+ /** @experimental The view-transition integration may change before 1.0. */
31
37
  interface ViewTransitionConfig {
32
38
  readonly enabled?: boolean;
33
39
  readonly skipInitialTransition?: boolean;
@@ -35,21 +41,43 @@ interface ViewTransitionConfig {
35
41
  }
36
42
  /** `'instant'`: flip now, load in background. `'preload-first'`: no raw-key flash. */
37
43
  type SwitchStrategy = 'instant' | 'preload-first';
44
+ /**
45
+ * Platform facts a loader needs to build a fetchable URL.
46
+ *
47
+ * `baseUrl` mirrors `document.baseURI`: on the browser it is the document's
48
+ * own base, on the server it is the document's `<base href>` resolved against
49
+ * the incoming request. It always describes a DIRECTORY-like base the way the
50
+ * browser sees it (a `<base href="/app/">` keeps its trailing slash; a
51
+ * `<base href="/app">` does not, exactly as in the browser).
52
+ */
53
+ interface LoaderContext {
54
+ /** Absolute base URL for relative dictionary paths. */
55
+ readonly baseUrl: string;
56
+ /** `true` when the application renders on the server (SSR / prerender). */
57
+ readonly isServer: boolean;
58
+ }
38
59
  /**
39
60
  * Pluggable key-dictionary loader. Returns a flat/nested JSON-compatible map
40
61
  * merged into `loadedTranslations` and read by key-based `translate(key)`.
41
62
  */
42
63
  interface TranslationLoader<L extends string = string> {
43
- load(language: L): Promise<Record<string, unknown>>;
64
+ load(language: L, context?: LoaderContext): Promise<Record<string, unknown>>;
44
65
  }
45
66
  /**
46
67
  * Lazy descriptor: `resolve()` dynamic-imports the real implementation, so
47
68
  * loader code splits out of the main bundle until first use. Resolved once
48
- * and cached by the service.
69
+ * and cached by the service. `context` lets a descriptor pick a
70
+ * platform-specific implementation (e.g. filesystem on the server).
49
71
  */
50
72
  interface LoaderDescriptor<L extends string = string> {
51
- resolve(): Promise<TranslationLoader<L>>;
73
+ resolve(context?: LoaderContext): Promise<TranslationLoader<L>>;
52
74
  }
75
+ /**
76
+ * The conventional `i18n/{language}.json` loader, and the service's default.
77
+ * Deliberately NOT code-split: it runs in the app initializer, so a lazy chunk
78
+ * would add two script round-trips (loader + its URL helper) before the first
79
+ * dictionary fetch. `httpLoader`/`remoteLoader` stay lazy — they are opt-in.
80
+ */
53
81
  export declare function jsonLoader(options?: {
54
82
  path?: string;
55
83
  }): LoaderDescriptor<string>;
@@ -65,13 +93,44 @@ interface RemoteLoaderOptions {
65
93
  }
66
94
  export declare function remoteLoader(options: RemoteLoaderOptions): LoaderDescriptor<string>;
67
95
  /** Wraps any function as a loader (mocks, in-memory, third-party SDKs). */
68
- export declare function customLoader<L extends string = string>(load: (language: L) => Promise<Record<string, unknown>>): LoaderDescriptor<L>;
96
+ export declare function customLoader<L extends string = string>(load: (language: L, context?: LoaderContext) => Promise<Record<string, unknown>>): LoaderDescriptor<L>;
97
+ /**
98
+ * Emitted (and optionally warned about) when `translate()` cannot resolve a
99
+ * key from the current dictionary, the fallback dictionary, or an explicit
100
+ * `defaultValue`.
101
+ *
102
+ * The event is reported **once per key per session**, no matter how many
103
+ * times a template re-renders it. `fallbackLanguage` is present only when a
104
+ * fallback is configured.
105
+ */
106
+ interface MissingKeyEvent<T extends string = string> {
107
+ readonly key: string;
108
+ readonly language: T;
109
+ readonly fallbackLanguage?: T;
110
+ }
111
+ /**
112
+ * Emitted (and optionally warned about) when a resolved message needs a named
113
+ * argument that the caller did not pass. Reported **once per (key, param)
114
+ * pair per session**; the placeholder stays in the output.
115
+ */
116
+ interface MissingParamEvent<T extends string = string> {
117
+ readonly key: string;
118
+ readonly param: string;
119
+ readonly language: T;
120
+ }
69
121
  /**
70
122
  * Global configuration for `@rivinia/i18n`.
71
123
  */
72
124
  interface RiviniaI18nConfig<T extends string = string> {
73
125
  readonly languages: readonly Language<T>[];
74
126
  readonly defaultLanguage: T;
127
+ /**
128
+ * Language used when a key is absent from the current dictionary. Must be
129
+ * one of `languages`. The fallback dictionary is loaded silently (it never
130
+ * drives `loadingState`), and its messages are rendered with the fallback
131
+ * language's locale — an English plural template keeps English plural rules.
132
+ */
133
+ readonly fallbackLanguage?: T;
75
134
  readonly storageKey?: string;
76
135
  readonly storageStrategy?: StorageStrategy;
77
136
  readonly autoApplyDirection?: boolean;
@@ -87,6 +146,37 @@ interface RiviniaI18nConfig<T extends string = string> {
87
146
  readonly switchStrategy?: SwitchStrategy;
88
147
  /** Called when a dictionary load fails. The service still falls back safely. */
89
148
  readonly onLoadError?: (language: T, error: unknown) => void;
149
+ /**
150
+ * Called when `translate()` cannot resolve a key (absent from the current
151
+ * dictionary, from the fallback dictionary, and with no `defaultValue`).
152
+ * Fires once per key per session. When set, the default console warning is
153
+ * suppressed.
154
+ */
155
+ readonly onMissingKey?: (event: MissingKeyEvent<T>) => void;
156
+ /**
157
+ * Log a `console.warn` (once per key) for unresolved keys.
158
+ * @default isDevMode() && !onMissingKey
159
+ */
160
+ readonly warnOnMissingKey?: boolean;
161
+ /**
162
+ * Called once per (key, param) pair when a message needs a named argument
163
+ * that `params` does not provide. The placeholder is still rendered
164
+ * unchanged. Delivered from a microtask, like `onMissingKey`.
165
+ */
166
+ readonly onMissingParam?: (event: MissingParamEvent<T>) => void;
167
+ /**
168
+ * Log a `console.warn` (once per key/param pair) for missing arguments.
169
+ * @default isDevMode() && !onMissingParam
170
+ */
171
+ readonly warnOnMissingParam?: boolean;
172
+ /**
173
+ * Persist the language to storage/cookie after a user-initiated switch
174
+ * (`setLanguage`, `toggle`, `next`, `previous`, `setLanguageAsync`). The
175
+ * initial language is never written, so a cookie is only set once the user
176
+ * actually chooses a language.
177
+ * @default true
178
+ */
179
+ readonly persist?: boolean;
90
180
  /**
91
181
  * Load the initial language during provider setup (before first paint).
92
182
  * SSR waits via `PendingTasks`. Set `false` to skip (e.g. fully inline apps
@@ -107,61 +197,111 @@ interface RiviniaI18nConfig<T extends string = string> {
107
197
  readonly detectBrowser?: boolean;
108
198
  }
109
199
  /**
110
- * Internal configuration token. Consumers must use `provideRiviniaI18n()`.
111
- * @internal
200
+ * A dictionary request that reached the network and failed.
201
+ *
202
+ * `statusText` is empty on HTTP/2 (measured: Chrome reports an empty string
203
+ * for a 404 over h2), so the message carries the numeric status instead.
204
+ * Passed to `RiviniaI18nConfig.onLoadError`.
112
205
  */
113
- declare const RIVINIA_I18N_CONFIG: InjectionToken<RiviniaI18nConfig<string>>;
114
- declare const DEFAULT_STORAGE_KEY = "rivinia.i18n.language";
115
- declare const DEFAULT_STORAGE_STRATEGY: StorageStrategy;
116
- declare const DEFAULT_AUTO_APPLY_DIRECTION = true;
117
- /** SSR-safe read. Returns `null` off-browser, on denial, or when missing. */
118
- declare function safeGetItem(key: string, strategy: StorageStrategy): string | null;
119
- /** SSR-safe write. Silently no-ops off-browser or on denial. */
120
- declare function safeSetItem(key: string, value: string, strategy: StorageStrategy): void;
206
+ export declare class RiviniaLoadError extends Error {
207
+ readonly url: string;
208
+ readonly status: number;
209
+ readonly language: string;
210
+ constructor(url: string, status: number, language: string, options?: {
211
+ cause?: unknown;
212
+ });
213
+ }
214
+ /**
215
+ * Typed-key registry. Empty by default, so `RegisteredI18nKey` resolves to
216
+ * `string` and nothing breaks.
217
+ *
218
+ * Augment it (usually with the generated file from `rivinia-i18n-keys`) to
219
+ * make every key-taking API type-checked:
220
+ *
221
+ * ```ts
222
+ * declare module '@rivinia/i18n' {
223
+ * interface RiviniaI18nKeyRegistry {
224
+ * readonly keys: 'app.title' | 'app.save';
225
+ * }
226
+ * }
227
+ * ```
228
+ *
229
+ * A genuinely dynamic key is asserted explicitly:
230
+ * ``i18n.translate(`status.${code}` as RegisteredI18nKey)``.
231
+ */
232
+ interface RiviniaI18nKeyRegistry {}
233
+ /** Every key accepted by `translate()`, `t()` and `RTranslatePipe`. */
234
+ type RegisteredI18nKey = RiviniaI18nKeyRegistry extends {
235
+ keys: infer K extends string;
236
+ } ? K : string;
121
237
  /**
122
238
  * Matches the browser language priority list against supported ids, in order.
123
239
  * For each browser entry (highest preference first) tries the exact tag, then
124
240
  * its base subtag (`ar-EG` → `ar`). Returns the first hit, or `null`.
125
241
  * Pure and exported for testing — pass `navigator.languages` in app code.
242
+ * @internal May move to an `@rivinia/i18n/internal` entry point before 1.0.
126
243
  */
127
244
  export declare function detectBrowserLanguage<T extends string>(supportedIds: readonly T[], browserLanguages: readonly string[] | undefined): T | null;
128
- /** Browser language list, `undefined` off-browser (SSR-safe input for detection). */
245
+ /**
246
+ * Browser language list, `undefined` off-browser (SSR-safe input for detection).
247
+ * @internal May move to an `@rivinia/i18n/internal` entry point before 1.0.
248
+ */
129
249
  export declare function browserLanguages(): readonly string[] | undefined;
130
250
  /**
131
251
  * Cookie helpers for the `'cookie'` storage strategy. Pure and SSR-testable:
132
252
  * the service supplies the header (server `REQUEST`) or `document.cookie`
133
253
  * (browser); these functions only parse and serialize.
134
254
  */
135
- /** Extracts a cookie value by name from a `Cookie` header or `document.cookie`. */
255
+ /**
256
+ * Extracts a cookie value by name from a `Cookie` header or `document.cookie`.
257
+ * @internal Exported for the package's own SSR tests; may move to an
258
+ * `@rivinia/i18n/internal` entry point before 1.0.
259
+ */
136
260
  export declare function parseCookie(header: string | null | undefined, name: string): string | null;
137
- /** Serializes a language cookie (Lax, root path, one year). */
261
+ /**
262
+ * Serializes a language cookie (Lax, root path, one year).
263
+ * @internal Exported for the package's own SSR tests; may move to an
264
+ * `@rivinia/i18n/internal` entry point before 1.0.
265
+ */
138
266
  export declare function serializeCookie(name: string, value: string, options?: {
139
267
  secure?: boolean;
140
268
  }): string;
141
269
  /**
142
- * Decides whether the language cookie gets `Secure`: only on `https:`, never
143
- * on `localhost` (dev TLS included — `Secure` there buys nothing and risks
144
- * silent persistence loss). Pure and SSR-safe: unknown locations → `false`.
145
- * The server never writes cookies regardless (app-owned responses).
270
+ * Tolerant hooks for one render. `onMissingParam` fires for each named
271
+ * argument that the message needs but `params` does not provide; the
272
+ * placeholder is still rendered unchanged.
146
273
  */
147
- declare function shouldSecureCookie(location: {
148
- protocol?: string;
149
- hostname?: string;
150
- } | null | undefined): boolean;
274
+ interface IcuFormatOptions {
275
+ readonly onMissingParam?: (name: string) => void;
276
+ }
151
277
  /**
152
- * Minimal ICU MessageFormat subset: `{name}` interpolation, `{n, plural, …}`,
153
- * `{x, select, …}`, `#` inside plurals, and nesting. Categories resolve via
154
- * the native `Intl.PluralRules(locale)` — Arabic gets all six forms
155
- * (zero/one/two/few/many/other) with zero extra dependencies.
278
+ * Minimal ICU MessageFormat (MF1) subset: `{name}` interpolation,
279
+ * `{n, plural, …}` (with `offset:`), `{n, selectordinal, …}`, `{x, select, …}`,
280
+ * `#` inside plural-style arguments, `{n, number[, style]}`, `{d, date[, style]}`,
281
+ * nesting, and ICU apostrophe quoting.
156
282
  *
157
283
  * Supported (and ONLY these — documented subset, translators beware):
158
284
  * - `{count, plural, =0 {none} one {# item} other {# items}}`
285
+ * - `{count, plural, offset:1 =0 {none} one {you and # other} other {you and # others}}`
286
+ * - `{place, selectordinal, one {#st} two {#nd} few {#rd} other {#th}}`
159
287
  * - `{gender, select, male {He} female {She} other {They}}`
288
+ * - `{amount, number}`, `{ratio, number, percent}`, `{count, number, integer}`,
289
+ * `{price, number, ::currency/USD}`
290
+ * - `{day, date}`, `{day, date, short|medium|long|full}`
160
291
  * - `{name}` plain interpolation (missing params keep the placeholder)
292
+ * - `''` → one apostrophe; `'{'…'}'` quotes a literal brace
293
+ *
294
+ * Offset semantics follow ICU (ICU4J `PluralFormat`): an explicit `=N` matches
295
+ * the RAW argument value, the plural category is selected with
296
+ * `value - offset`, and `#` renders `value - offset` in the locale's digits.
297
+ *
298
+ * Templates are compiled once into an AST and cached (bounded LRU), so a
299
+ * template rendered on every change-detection pass is not re-parsed.
161
300
  *
162
- * Malformed input never throws: the raw segment is returned as-is.
301
+ * Unsupported or malformed constructs never throw: the raw `{…}` segment is
302
+ * returned as-is and parsing continues after it.
163
303
  */
164
- export declare function formatIcu(template: string, params: TranslateParams, locale: string): string;
304
+ export declare function formatIcu(template: string, params: TranslateParams, locale: string, options?: IcuFormatOptions): string;
165
305
  /**
166
306
  * Headless language owner. State (signals, readonly): current language,
167
307
  * direction, loader status, dictionaries. Changes only via the methods below.
@@ -174,6 +314,10 @@ export declare class RiviniaI18n<L extends string = string> {
174
314
  private readonly _storageKey;
175
315
  private readonly _storageStrategy;
176
316
  private readonly _autoApplyDirection;
317
+ /** Writes reach storage/cookies only after an explicit switch (RIV-17). */
318
+ private readonly _persist;
319
+ /** Validated once; `null` means no fallback chain. */
320
+ private readonly _fallbackId;
177
321
  /**
178
322
  * Injected (not global) document: the dir/lang effect renders on the
179
323
  * server too, avoiding an RTL first-paint shift on hydration.
@@ -183,9 +327,21 @@ export declare class RiviniaI18n<L extends string = string> {
183
327
  /** Present only on the server: used for cookie reads + transfer writes. */
184
328
  private readonly _request;
185
329
  private readonly _transfer;
330
+ /**
331
+ * Platform facts for loaders, built once: `REQUEST` + `<base href>` on the
332
+ * server, `document.baseURI` in the browser. This is what makes the default
333
+ * loader work under SSR instead of fetching a relative URL Node cannot parse.
334
+ */
335
+ readonly loaderContext: LoaderContext;
186
336
  private readonly _currentLanguageId;
187
337
  private readonly _languages;
188
338
  private readonly _loadedTranslations;
339
+ /**
340
+ * The fallback dictionary, kept separate from `_loadedTranslations` (which
341
+ * always mirrors the VISIBLE language). A signal so `t()`'s computed
342
+ * re-evaluates when the fallback arrives.
343
+ */
344
+ private readonly _fallbackDict;
189
345
  /**
190
346
  * Explicit loader wins; otherwise the conventional JSON layout
191
347
  * (`i18n/{language}.json` — files in `public/i18n/`, served from the site
@@ -196,7 +352,15 @@ export declare class RiviniaI18n<L extends string = string> {
196
352
  private readonly _getLoader;
197
353
  private _resolvedLoader;
198
354
  private readonly _translationsCache;
355
+ /**
356
+ * Per-language generation, bumped by `reload()`. A load captures the
357
+ * generation before its request and discards the response when it moved:
358
+ * a stale dictionary can never reach the cache or the signals.
359
+ */
360
+ private readonly _generations;
199
361
  private readonly _inflight;
362
+ /** Non-background loads in flight; `loadingState` follows this count. */
363
+ private _loadingCount;
200
364
  /**
201
365
  * Out-of-order safety: a response reaches the visible signals only when it
202
366
  * belongs to the currently intended language (`_currentLanguageId()`).
@@ -206,25 +370,55 @@ export declare class RiviniaI18n<L extends string = string> {
206
370
  private _applyCount;
207
371
  private _initialized;
208
372
  private readonly _tasks;
209
- readonly languageChanged: import("@angular/core").Signal<L>;
210
- readonly languages: import("@angular/core").Signal<readonly Language<L>[]>;
211
- readonly currentLanguage: import("@angular/core").Signal<L>;
212
- readonly currentLanguageObject: import("@angular/core").Signal<Language<L>>;
213
- readonly dir: import("@angular/core").Signal<Direction>;
214
- readonly isRtl: import("@angular/core").Signal<boolean>;
373
+ /**
374
+ * @deprecated Use `currentLanguage`, which is the same signal.
375
+ * Scheduled for removal before 1.0.
376
+ */
377
+ readonly languageChanged: Signal<L>;
378
+ readonly languages: Signal<readonly Language<L>[]>;
379
+ readonly currentLanguage: Signal<L>;
380
+ readonly currentLanguageObject: Signal<Language<L>>;
381
+ readonly dir: Signal<Direction>;
382
+ readonly isRtl: Signal<boolean>;
215
383
  private readonly _loadingState;
216
384
  private readonly _loadingError;
217
385
  /** Loader state for skeletons/spinners. */
218
- readonly loadingState: import("@angular/core").Signal<"idle" | "loading" | "error">;
219
- readonly loadingError: import("@angular/core").Signal<unknown>;
220
- readonly isLoading: import("@angular/core").Signal<boolean>;
386
+ readonly loadingState: Signal<"idle" | "loading" | "error">;
387
+ readonly loadingError: Signal<unknown>;
388
+ readonly isLoading: Signal<boolean>;
221
389
  private readonly _ready;
222
390
  /**
223
391
  * True once the initial language content is available (inline seed and/or
224
392
  * initial load settled) — or immediately when `preload: false` skips setup
225
393
  * loading. Gate first-paint skeletons on this, not on `isLoading`.
226
394
  */
227
- readonly ready: import("@angular/core").Signal<boolean>;
395
+ readonly ready: Signal<boolean>;
396
+ /**
397
+ * Missing-key reporting. `warnOnMissingKey` defaults to dev-mode warnings
398
+ * unless the consumer supplied a handler (then the handler owns reporting).
399
+ */
400
+ private readonly _warnOnMissingKey;
401
+ private readonly _missingKeys;
402
+ private readonly _reportedMissingKeys;
403
+ private readonly _pendingMissingKeys;
404
+ private readonly _pendingMissingEvents;
405
+ private _missingFlushQueued;
406
+ private readonly _warnOnMissingParam;
407
+ /** Dedupe key: `key` + NUL + `param`, so neither part can collide. */
408
+ private readonly _reportedMissingParams;
409
+ private readonly _pendingMissingParams;
410
+ private _missingParamsFlushQueued;
411
+ /**
412
+ * Keys that could not be resolved from the current dictionary, the fallback
413
+ * dictionary, or a `defaultValue`, in the order they were first looked up.
414
+ * Published in a microtask because `t()` is a `computed` and Angular forbids
415
+ * signal writes inside a computation.
416
+ */
417
+ readonly missingKeys: Signal<readonly string[]>;
418
+ /** Resets the report (and the once-per-key dedupe), e.g. after a fix. */
419
+ clearMissingKeys(): void;
420
+ /** Resets the missing-parameter dedupe, e.g. after adding the argument. */
421
+ clearMissingParams(): void;
228
422
  constructor();
229
423
  getLanguage(id: L): Language<L> | undefined;
230
424
  /**
@@ -235,14 +429,52 @@ export declare class RiviniaI18n<L extends string = string> {
235
429
  * `loadingError`/`onLoadError`, inline seeds are preserved).
236
430
  */
237
431
  initialize(): Promise<void>;
238
- translate(key: string, defaultValue?: string, params?: TranslateParams): string;
239
- translate(key: string, params?: TranslateParams): string;
432
+ translate(key: RegisteredI18nKey, defaultValue?: string, params?: TranslateParams): string;
433
+ translate(key: RegisteredI18nKey, params?: TranslateParams): string;
240
434
  translate(translations: Translation<L>): string;
241
- loadedTranslations: import("@angular/core").Signal<Record<string, unknown>>;
435
+ /**
436
+ * A `computed` over the same resolution chain as `translate()` — for
437
+ * component fields (`readonly title = i18n.t('home.title')`), not for
438
+ * calling from a template expression on every change detection.
439
+ *
440
+ * A function `params` is invoked inside the computation, so the signals it
441
+ * reads are tracked and a change re-renders the text.
442
+ */
443
+ t(key: RegisteredI18nKey): Signal<string>;
444
+ t(key: RegisteredI18nKey, params: TranslateParams | (() => TranslateParams)): Signal<string>;
445
+ t(key: RegisteredI18nKey, defaultValue: string, params?: TranslateParams | (() => TranslateParams)): Signal<string>;
446
+ private _resolveKeyText;
447
+ loadedTranslations: Signal<Record<string, unknown>>;
242
448
  /** Preload without switching (use in `APP_INITIALIZER` / route guards). */
243
449
  loadTranslations(languageId: L, opts?: {
244
450
  silent?: boolean;
245
451
  }): Promise<Record<string, unknown>>;
452
+ /**
453
+ * Invalidates cached dictionaries and reloads them from the loader.
454
+ *
455
+ * - `reload()` — refreshes the current language (and the fallback, when
456
+ * configured) and drops every OTHER cached dictionary, so the next switch
457
+ * refetches. Resolves `true` when the current language loaded.
458
+ * - `reload(lang)` — refreshes one language. If it is the current one it is
459
+ * applied; otherwise it is only re-cached (and refreshed in the fallback
460
+ * slot when it is the fallback).
461
+ *
462
+ * The visible dictionary stays on screen until the fresh one arrives
463
+ * (stale-while-revalidate), so a reload never flashes raw keys.
464
+ *
465
+ * Never rejects: failures land on `loadingState`, `loadingError` and
466
+ * `onLoadError` exactly like `loadTranslations`.
467
+ */
468
+ reload(languageId?: L): Promise<boolean>;
469
+ private _reloadOne;
470
+ private _generationOf;
471
+ private _invalidate;
472
+ /**
473
+ * Flips between the first two configured languages. Documentation and
474
+ * templates commonly place it next to `next()`/`previous()`, so it warns in
475
+ * dev mode when more than two languages are configured — use the cycling
476
+ * methods there.
477
+ */
246
478
  toggle(): void;
247
479
  next(): void;
248
480
  previous(): void;
@@ -255,13 +487,46 @@ export declare class RiviniaI18n<L extends string = string> {
255
487
  /** Date/time formatting bound to the current language locale (cached Intl). */
256
488
  formatDate(value: Date | number, options?: Intl.DateTimeFormatOptions): string;
257
489
  /** BCP-47 locale driving Intl + ICU plural rules (falls back to the id). */
258
- readonly locale: import("@angular/core").Signal<string>;
490
+ readonly locale: Signal<string>;
259
491
  private readonly _formatters;
260
492
  private numberFormatter;
261
493
  private dateTimeFormatter;
262
494
  private applyLanguage;
495
+ private _persistLanguage;
263
496
  private render;
497
+ /**
498
+ * Current dictionary first, then the fallback dictionary. The returned
499
+ * locale belongs to the dictionary the text came from: an English plural
500
+ * template borrowed by an Arabic UI must use English plural rules.
501
+ */
502
+ private _lookupKey;
503
+ private _localeOf;
504
+ /** Loads the fallback in the background when it is not cached yet. */
505
+ private _ensureFallback;
506
+ private _hasDictionary;
507
+ /**
508
+ * Records a key no dictionary could resolve. Once per key per session; the
509
+ * signal write is deferred to a microtask so `t()` can stay a pure
510
+ * `computed` (Angular forbids signal writes inside a computation).
511
+ */
512
+ private _reportMissingKey;
513
+ private _queueMissingFlush;
514
+ /**
515
+ * Mirrors `_reportMissingKey` for absent message arguments. The output keeps
516
+ * the placeholder; this only records/warns, once per (key, param) pair. The
517
+ * hook is deferred to a microtask for the same NG0600 reason.
518
+ */
519
+ private _reportMissingParam;
520
+ private _queueMissingParamsFlush;
264
521
  private _loadTranslations;
522
+ /**
523
+ * A dictionary reaches the visible signals only when its language is
524
+ * current at resolution time; a fallback dictionary fills the fallback slot.
525
+ * Everything else stays cached for the next switch.
526
+ */
527
+ private _applyDictionary;
528
+ /** Fetch + cache + transfer. Shared by every caller; never applies. */
529
+ private _fetchDictionary;
265
530
  /**
266
531
  * Reads the persisted language. Cookie strategy: server reads the request
267
532
  * `Cookie` header (no hydration mismatch), browser reads `document.cookie`.
@@ -275,6 +540,10 @@ export declare class RiviniaI18n<L extends string = string> {
275
540
  private readTransfer;
276
541
  /** Stores freshly loaded dictionaries for hydration (server only). */
277
542
  private writeTransfer;
543
+ /**
544
+ * Exact key first, then the nested walk. Exports from some tools keep the
545
+ * dot in the key (`{ "app.title": "x" }`); on a collision the flat key wins.
546
+ */
278
547
  private _resolveKey;
279
548
  private _resolveInitialLanguage;
280
549
  static ɵfac: i0.ɵɵFactoryDeclaration<RiviniaI18n<any>, never>;
@@ -323,7 +592,11 @@ export declare function defineRiviniaI18n<L extends string>(config: RiviniaI18nC
323
592
  provide: () => EnvironmentProviders;
324
593
  inject: () => RiviniaI18n<L>;
325
594
  };
326
- /** Progressive-enhancement wrapper around the View Transition API. */
595
+ /**
596
+ * Progressive-enhancement wrapper around the View Transition API.
597
+ * @internal Driven by `RiviniaI18n`; consumers configure
598
+ * `viewTransition` instead of injecting this service.
599
+ */
327
600
  export declare class ViewTransitionService {
328
601
  private readonly _doc;
329
602
  run(callback: () => void): void;
@@ -335,14 +608,15 @@ export declare class ViewTransitionService {
335
608
  *
336
609
  * Impure (`pure: false`) by necessity: the service reads signals on every
337
610
  * call, and a pure pipe would not re-evaluate on language switches. For long
338
- * lists prefer `translate()` in component code over this pipe.
611
+ * lists prefer `translate()` in component code — or `t()`, which returns a
612
+ * signal a template can read without re-running the pipe.
339
613
  */
340
614
  export declare class RTranslatePipe<L extends string = string> {
341
615
  private readonly _i18n;
342
- transform(key: string, defaultValue?: string, params?: TranslateParams): string;
343
- transform(key: string, params?: TranslateParams): string;
616
+ transform(key: RegisteredI18nKey, defaultValue?: string, params?: TranslateParams): string;
617
+ transform(key: RegisteredI18nKey, params?: TranslateParams): string;
344
618
  transform(translations: Translation<L>): string;
345
619
  static ɵfac: i0.ɵɵFactoryDeclaration<RTranslatePipe<any>, never>;
346
620
  static ɵpipe: i0.ɵɵPipeDeclaration<RTranslatePipe<any>, "rTranslate", true>;
347
621
  }
348
- export type { Direction, HttpLoaderOptions, Language, LoaderDescriptor, RemoteLoaderOptions, RiviniaI18nConfig, StorageStrategy, SwitchStrategy, TranslateParams, Translation, TranslationLoader, ViewTransitionConfig, ViewTransitionInfo };
622
+ export type { Direction, HttpLoaderOptions, IcuFormatOptions, Language, LoaderContext, LoaderDescriptor, MissingKeyEvent, MissingParamEvent, RegisteredI18nKey, RemoteLoaderOptions, RiviniaI18nConfig, RiviniaI18nKeyRegistry, StorageStrategy, SwitchStrategy, TranslateParams, Translation, TranslationLoader, ViewTransitionConfig, ViewTransitionInfo };
@@ -1,15 +0,0 @@
1
- var HttpLoader = class {
2
- _options;
3
- constructor(_options) {
4
- this._options = _options;
5
- }
6
- async load(language) {
7
- const url = this._options.buildUrl?.(language) ?? `${this._options.endpoint}/${language}`;
8
- const response = await fetch(url, { method: this._options.method ?? "GET" });
9
- if (!response.ok) throw new Error(`[rivinia/i18n] Failed to load "${url}": ${response.statusText}`);
10
- return response.json();
11
- }
12
- };
13
- export { HttpLoader };
14
-
15
- //# sourceMappingURL=rivinia-i18n-http-loader.impl-DVlKmSDL.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"rivinia-i18n-http-loader.impl-DVlKmSDL.mjs","names":[],"sources":["../../../projects/i18n/src/lib/http-loader.impl.ts"],"sourcesContent":["import type { HttpLoaderOptions, TranslationLoader } from './loaders';\n\nexport class HttpLoader<L extends string = string> implements TranslationLoader<L> {\n constructor(private readonly _options: HttpLoaderOptions) {}\n\n async load(language: L): Promise<Record<string, unknown>> {\n const url = this._options.buildUrl?.(language) ?? `${this._options.endpoint}/${language}`;\n const response = await fetch(url, { method: this._options.method ?? 'GET' });\n if (!response.ok) {\n throw new Error(`[rivinia/i18n] Failed to load \"${url}\": ${response.statusText}`);\n }\n return response.json();\n }\n}\n"],"mappings":"AAEA,IAAa,aAAb,MAAuB;CACQ;CAA7B,YAA6B,UAA2B;EAA3B,KAAA,WAAA;CAA8B;CAE3D,MAAM,KAAK,UAAW;EACpB,MAAM,MAAM,KAAK,SAAS,WAAW,QAAQ,KAAK,GAAG,KAAK,SAAS,SAAQ,GAAI;EAC/E,MAAM,WAAW,MAAM,MAAM,KAAK,EAAE,QAAQ,KAAK,SAAS,UAAU,MAAK,CAAE;EAC3E,IAAI,CAAC,SAAS,IACZ,MAAM,IAAI,MAAM,kCAAkC,IAAG,KAAM,SAAS,YAAY;EAElF,OAAO,SAAS,KAAI;CACtB;AACD"}
@@ -1,16 +0,0 @@
1
- const DEFAULT_BASE_PATH = "i18n";
2
- var JsonLoader = class {
3
- _options;
4
- constructor(_options) {
5
- this._options = _options;
6
- }
7
- async load(language) {
8
- const url = `${this._options?.path ?? DEFAULT_BASE_PATH}/${language}.json`;
9
- const response = await fetch(url);
10
- if (!response.ok) throw new Error(`[rivinia/i18n] Failed to load "${url}": ${response.statusText}`);
11
- return response.json();
12
- }
13
- };
14
- export { JsonLoader };
15
-
16
- //# sourceMappingURL=rivinia-i18n-json-loader.impl-VXwAmyWL.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"rivinia-i18n-json-loader.impl-VXwAmyWL.mjs","names":[],"sources":["../../../projects/i18n/src/lib/json-loader.impl.ts"],"sourcesContent":["import type { TranslationLoader } from './loaders';\n\nconst DEFAULT_BASE_PATH = 'i18n';\n\nexport class JsonLoader<L extends string = string> implements TranslationLoader<L> {\n constructor(private readonly _options?: { path?: string }) {}\n\n async load(language: L): Promise<Record<string, unknown>> {\n const basePath = this._options?.path ?? DEFAULT_BASE_PATH;\n const url = `${basePath}/${language}.json`;\n const response = await fetch(url);\n if (!response.ok) {\n throw new Error(`[rivinia/i18n] Failed to load \"${url}\": ${response.statusText}`);\n }\n return response.json();\n }\n}\n"],"mappings":"AAEA,MAAM,oBAAoB;AAE1B,IAAa,aAAb,MAAuB;CACQ;CAA7B,YAA6B,UAA4B;EAA5B,KAAA,WAAA;CAA+B;CAE5D,MAAM,KAAK,UAAW;EAEpB,MAAM,MAAM,GADK,KAAK,UAAU,QAAQ,kBACjB,GAAI,SAAQ;EACnC,MAAM,WAAW,MAAM,MAAM,GAAG;EAChC,IAAI,CAAC,SAAS,IACZ,MAAM,IAAI,MAAM,kCAAkC,IAAG,KAAM,SAAS,YAAY;EAElF,OAAO,SAAS,KAAI;CACtB;AACD"}
@@ -1,15 +0,0 @@
1
- var RemoteLoader = class {
2
- _options;
3
- constructor(_options) {
4
- this._options = _options;
5
- }
6
- async load(language) {
7
- const url = this._options.url(language);
8
- const response = await fetch(url, { headers: this._options.headers });
9
- if (!response.ok) throw new Error(`[rivinia/i18n] Failed to load "${url}": ${response.statusText}`);
10
- return response.json();
11
- }
12
- };
13
- export { RemoteLoader };
14
-
15
- //# sourceMappingURL=rivinia-i18n-remote-loader.impl-XKqdLHoJ.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"rivinia-i18n-remote-loader.impl-XKqdLHoJ.mjs","names":[],"sources":["../../../projects/i18n/src/lib/remote-loader.impl.ts"],"sourcesContent":["import type { RemoteLoaderOptions, TranslationLoader } from './loaders';\n\nexport class RemoteLoader<L extends string = string> implements TranslationLoader<L> {\n constructor(private readonly _options: RemoteLoaderOptions) {}\n\n async load(language: L): Promise<Record<string, unknown>> {\n const url = this._options.url(language);\n const response = await fetch(url, { headers: this._options.headers });\n if (!response.ok) {\n throw new Error(`[rivinia/i18n] Failed to load \"${url}\": ${response.statusText}`);\n }\n return response.json();\n }\n}\n"],"mappings":"AAEA,IAAa,eAAb,MAAyB;CACM;CAA7B,YAA6B,UAA6B;EAA7B,KAAA,WAAA;CAAgC;CAE7D,MAAM,KAAK,UAAW;EACpB,MAAM,MAAM,KAAK,SAAS,IAAI,QAAQ;EACtC,MAAM,WAAW,MAAM,MAAM,KAAK,EAAE,SAAS,KAAK,SAAS,QAAO,CAAE;EACpE,IAAI,CAAC,SAAS,IACZ,MAAM,IAAI,MAAM,kCAAkC,IAAG,KAAM,SAAS,YAAY;EAElF,OAAO,SAAS,KAAI;CACtB;AACD"}