@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.
package/README.md CHANGED
@@ -3,218 +3,505 @@
3
3
  [![npm version](https://img.shields.io/npm/v/@rivinia/i18n.svg)](https://www.npmjs.com/package/@rivinia/i18n)
4
4
  [![license](https://img.shields.io/npm/l/@rivinia/i18n.svg)](https://www.npmjs.com/package/@rivinia/i18n)
5
5
 
6
- A headless Angular language manager built on signals. It supports key-based
7
- JSON dictionaries, inline translations, RTL/LTR document attributes, lazy
8
- loaders, ICU plural/select messages, browser-language detection, and
9
- ECMAScript internationalization number/date formatting.
6
+ A headless Angular language manager built on signals. Key-based JSON
7
+ dictionaries, inline translations, RTL/LTR document attributes, lazy loaders,
8
+ ICU plural/select messages, browser-language detection, and `Intl` number/date
9
+ formatting — with SSR that actually works and no runtime dependency beyond
10
+ Angular.
11
+
12
+ - Package version: **0.4.0**
13
+ - Peer dependency: **`@angular/core` `^22.0.0`** (plus `@angular-devkit/schematics` for `ng add`)
14
+ - Entry point: **`@rivinia/i18n`** (single public entry point)
15
+ - `sideEffects: false`; no runtime import beyond `@angular/core`; loaders are lazy chunks
16
+ - No `HttpClient` peer — the built-in loaders use `fetch`
17
+
18
+ ## Quick features
19
+
20
+ - **Signal-first state.** `currentLanguage`, `dir`, `loadingState`, `missingKeys` and
21
+ `locale` are readonly signals; changes only via methods.
22
+ - **Zero-config dictionaries.** `jsonLoader()` reads `i18n/{language}.json` — the
23
+ `public/i18n/` layout Angular serves at the site root.
24
+ - **SSR-correct URLs.** On the server the loader builds an absolute URL from
25
+ `REQUEST` + `<base href>`; the browser uses `document.baseURI`.
26
+ - **TransferState hydration.** Dictionaries rendered on the server are not fetched again
27
+ by the client (measured in the e2e app).
28
+ - **Fallback language.** Current dictionary → fallback dictionary → `defaultValue` → key.
29
+ Fallback text keeps the fallback locale's plural rules.
30
+ - **Missing-key reporting.** `onMissingKey`, a `missingKeys` signal, and a dev-mode
31
+ warning — once per key per session, never a false positive during loading.
32
+ - **`reload()`.** Stale-while-revalidate: the visible dictionary stays on screen until
33
+ the fresh one arrives.
34
+ - **ICU subset with the six Arabic plural forms.** `plural`, `selectordinal`, `offset:`,
35
+ `select`, `number`/`date` styles, nesting, and `#`.
36
+ - **`t()` returns a `Signal<string>`**, so a field re-renders on a language switch or on a
37
+ signal read by its params function.
38
+ - **Typed keys.** A generated `.d.ts` turns a typo into a compile error; without it every
39
+ string key stays legal.
40
+ - **Persistence + detection.** local/session/cookie storage, `navigator.languages` match,
41
+ `<html lang>` and `<html dir>` kept in sync.
42
+
43
+ ## Install
10
44
 
11
- - Package version: **0.3.2**
12
- - Peer dependency: **`@angular/core` `^22.0.0`**
13
- - No `tslib` or `HttpClient` peer dependency. Built-in loaders use `fetch`.
45
+ ```bash
46
+ npm install @rivinia/i18n
47
+ pnpm add @rivinia/i18n
48
+ yarn add @rivinia/i18n
49
+ bun add @rivinia/i18n
50
+ ```
14
51
 
15
- ## Install and configure
52
+ With the CLI schematic (wires a starter provider into `app.config.ts`):
16
53
 
17
54
  ```bash
18
- npm install @rivinia/i18n
19
55
  ng add @rivinia/i18n
20
56
  ```
21
57
 
22
- `ng add` prompts for language IDs and whether to enable browser detection; the
23
- first language becomes the default. It wires a starter provider into a
24
- standalone app's `app.config.ts`. You can configure it yourself instead:
58
+ `ng add` asks for the language ids (comma-separated; the first is the default) and
59
+ whether to detect the browser language. It only inserts an import and a
60
+ `provideRiviniaI18n({…})` call, is idempotent, and skips with a warning — never an
61
+ error — when it does not recognize the workspace.
62
+
63
+ ## Imports
64
+
65
+ ```ts
66
+ import {
67
+ provideRiviniaI18n,
68
+ defineRiviniaI18n,
69
+ injectRiviniaI18n,
70
+ RiviniaI18n,
71
+ RTranslatePipe,
72
+ jsonLoader,
73
+ httpLoader,
74
+ remoteLoader,
75
+ customLoader,
76
+ formatIcu,
77
+ } from '@rivinia/i18n';
78
+ ```
79
+
80
+ ## API stability
81
+
82
+ Every export is classified so the 1.0 freeze is predictable. **Internal** symbols
83
+ exist only so the package's own tests can import them; they may move to an
84
+ `@rivinia/i18n/internal` entry point (or disappear) before 1.0.
85
+
86
+ | Export | Kind | Tier |
87
+ | ------------------------------------------------------------------------------------- | ---------------- | ------------ |
88
+ | `RiviniaI18n` | service | Stable |
89
+ | `provideRiviniaI18n`, `defineRiviniaI18n`, `injectRiviniaI18n` | providers | Stable |
90
+ | `RTranslatePipe` | pipe | Stable |
91
+ | `RiviniaI18nConfig` | type | Stable |
92
+ | `Language`, `Direction`, `Translation`, `TranslateParams`, `StorageStrategy`, `SwitchStrategy` | types | Stable |
93
+ | `RiviniaLoadError` | class | Stable |
94
+ | `MissingKeyEvent`, `MissingParamEvent` | types | Stable |
95
+ | `TranslationLoader`, `LoaderDescriptor`, `LoaderContext` | types | Stable |
96
+ | `jsonLoader`, `httpLoader`, `remoteLoader`, `customLoader` | loader factories | Stable |
97
+ | `HttpLoaderOptions`, `RemoteLoaderOptions` | types | Stable |
98
+ | `formatIcu`, `IcuFormatOptions` | ICU API | Stable |
99
+ | `RegisteredI18nKey`, `RiviniaI18nKeyRegistry` | typed-keys types | Stable |
100
+ | `ViewTransitionConfig`, `ViewTransitionInfo` | types | Experimental |
101
+ | `ViewTransitionService` | service | Internal |
102
+ | `parseCookie`, `serializeCookie` | cookie helpers | Internal |
103
+ | `browserLanguages`, `detectBrowserLanguage` | helpers | Internal |
104
+
105
+ `languageChanged` is deprecated: `currentLanguage` is the same signal.
106
+
107
+ ## Quick start
25
108
 
26
109
  ```ts
27
110
  // src/app/i18n.config.ts
28
- import { defineRiviniaI18n, jsonLoader } from '@rivinia/i18n';
111
+ import { defineRiviniaI18n } from '@rivinia/i18n';
29
112
 
30
- export const i18nConfig = defineRiviniaI18n({
31
- defaultLanguage: 'en',
113
+ export const i18n = defineRiviniaI18n({
114
+ defaultLanguage: 'ar',
32
115
  languages: [
33
- { id: 'en', nativeName: 'English', dir: 'ltr', locale: 'en-US' },
34
116
  { id: 'ar', nativeName: 'العربية', dir: 'rtl', locale: 'ar-EG' },
117
+ { id: 'en', nativeName: 'English', dir: 'ltr', locale: 'en-GB' },
35
118
  ],
36
- detectBrowser: true,
37
- switchStrategy: 'preload-first',
38
- loader: jsonLoader(),
119
+ fallbackLanguage: 'en',
39
120
  });
40
121
  ```
41
122
 
42
123
  ```ts
43
124
  // src/app/app.config.ts
44
125
  import type { ApplicationConfig } from '@angular/core';
45
- import { i18nConfig } from './i18n.config';
126
+ import { i18n } from './i18n.config';
46
127
 
47
128
  export const appConfig: ApplicationConfig = {
48
- providers: [i18nConfig.provide()],
129
+ providers: [i18n.provide()],
49
130
  };
50
131
  ```
51
132
 
52
- `defineRiviniaI18n()` binds the config to typed accessors, so
53
- `i18nConfig.inject()` retains the `'en' | 'ar'` language type. Alternatively,
54
- use `provideRiviniaI18n(config)` in the providers array and
55
- `injectRiviniaI18n<'en' | 'ar'>()` in an injection context.
56
-
57
- Defaults: `preload: true`, `detectBrowser: false`, local-storage persistence,
58
- and automatic `<html lang>`/`<html dir>` updates. A stored supported language
59
- always wins over browser detection. Use `storageStrategy: 'none'` to disable
60
- persistence; `'session'` and `'cookie'` are also supported.
61
-
62
- ## Dictionaries
63
-
64
- By default, `jsonLoader()` fetches `i18n/{language}.json` from the site root.
65
- For Angular apps using the standard `public/` static-file directory, put
66
- dictionaries at `public/i18n/en.json`, `public/i18n/ar.json`, and so on. Make
67
- sure your host serves those files at `/i18n/{language}.json`.
133
+ ```ts
134
+ // src/app/header.ts
135
+ import { Component } from '@angular/core';
136
+ import { RTranslatePipe } from '@rivinia/i18n';
137
+ import { i18n } from './i18n.config';
68
138
 
69
- If an existing app still serves dictionaries from `assets/i18n/`, keep that
70
- layout with `jsonLoader({ path: 'assets/i18n' })` instead.
139
+ @Component({
140
+ selector: 'app-header',
141
+ imports: [RTranslatePipe],
142
+ template: `
143
+ <h1>{{ title() }}</h1>
144
+ <p>{{ 'booking.seats' | rTranslate: { count: seats } }}</p>
145
+ <button type="button" (click)="use('en')">English</button>
146
+ `,
147
+ })
148
+ export class Header {
149
+ private readonly service = i18n.inject();
150
+ readonly title = this.service.t('app.title');
151
+ readonly seats = 3;
71
152
 
72
- ```json
73
- // public/i18n/en.json
74
- {
75
- "booking": {
76
- "seats": "{count, plural, =0 {No seats} one {# seat} other {# seats}}"
153
+ use(id: 'ar' | 'en'): void {
154
+ this.service.setLanguage(id);
77
155
  }
78
156
  }
79
157
  ```
80
158
 
81
- ```json
82
- // public/i18n/ar.json
83
- {
84
- "booking": {
85
- "seats": "{count, plural, zero {لا مقاعد} one {مقعد واحد} two {مقعدان} few {# مقاعد} many {# مقعدًا} other {# مقعد}}"
86
- }
87
- }
88
- ```
159
+ `defineRiviniaI18n()` keeps the `'ar' | 'en'` union through `provide()` and `inject()`.
160
+ `provideRiviniaI18n(config)` + `injectRiviniaI18n<'ar' | 'en'>()` do the same without the
161
+ wrapper.
162
+
163
+ `provideRiviniaI18n()` registers an app initializer that loads the initial language
164
+ before first paint (SSR waits through `PendingTasks`). `ready()` becomes true when the
165
+ first content is available or initial loading has settled.
166
+
167
+ ## Configuration
168
+
169
+ | Option | Type | Default | Meaning |
170
+ | -------------------- | ------------------------------------------- | ---------------------------------- | --------------------------------------------------------------------------- |
171
+ | `languages` | `readonly Language<T>[]` | — | Supported languages (`id`, `nativeName`, `dir`, optional `locale`). |
172
+ | `defaultLanguage` | `T` | — | Must be one of `languages`; validated at construction. |
173
+ | `fallbackLanguage` | `T` | none | Second lookup dictionary; must be one of `languages`. |
174
+ | `loader` | `LoaderDescriptor<T>` | `jsonLoader()` | Dictionary source. |
175
+ | `translations` | `Partial<Record<T, Record<string, unknown>>>` | none | Inline seeds, painted before any network load; a loader response still wins. |
176
+ | `preload` | `boolean` | `true` | Load the initial language during provider setup. |
177
+ | `detectBrowser` | `boolean` | `false` | Match `navigator.languages` on first visit (a stored choice wins). |
178
+ | `storageStrategy` | `'local' \| 'session' \| 'cookie' \| 'none'` | `'local'` | Persistence; `'cookie'` also works on the server through `REQUEST`. |
179
+ | `storageKey` | `string` | `'rivinia.i18n.language'` | Storage key. |
180
+ | `switchStrategy` | `'instant' \| 'preload-first'` | `'instant'` | `'preload-first'` waits for the dictionary; a failure keeps the old language. |
181
+ | `autoApplyDirection` | `boolean` | `true` | Write `<html lang>` and `<html dir>`. |
182
+ | `onLoadError` | `(language, error) => void` | none | Dictionary load failure. Initialization never rejects because of it. |
183
+ | `onMissingKey` | `(event) => void` | none | Unresolved key; suppresses the default warning. |
184
+ | `warnOnMissingKey` | `boolean` | `isDevMode() && !onMissingKey` | `console.warn` once per key. |
185
+ | `onMissingParam` | `(event) => void` | none | Missing message argument; suppresses the default warning. |
186
+ | `warnOnMissingParam` | `boolean` | `isDevMode() && !onMissingParam` | `console.warn` once per (key, param). |
187
+ | `persist` | `boolean` | `true` | Persist the language after an explicit switch. First load writes nothing. |
188
+ | `viewTransition` | `ViewTransitionConfig` | none | Document view transition on language change. |
189
+
190
+ ## Dictionaries
89
191
 
90
- The default loader does not use `HttpClient`. To use a different JSON path or
91
- an endpoint, pass a loader descriptor:
192
+ The default loader fetches `i18n/{language}.json`. For a standard Angular app that
193
+ means `public/i18n/en.json` served as `/i18n/en.json`. An existing
194
+ `assets/i18n/` layout is one option away:
92
195
 
93
196
  ```ts
94
197
  import { httpLoader, jsonLoader, remoteLoader } from '@rivinia/i18n';
95
198
 
96
- jsonLoader({ path: '/my-i18n' }); // fetches /my-i18n/{language}.json
97
- httpLoader({ endpoint: 'https://api.example.com/i18n' }); // appends /{language}
199
+ jsonLoader(); // /i18n/{language}.json
200
+ jsonLoader({ path: 'assets/i18n' }); // /assets/i18n/{language}.json
201
+ httpLoader({ endpoint: 'https://api.example.com/i18n' }); // …/{language}
98
202
  remoteLoader({
99
203
  url: (language) => `https://api.example.com/v2/${language}`,
100
204
  headers: { Authorization: 'Bearer …' },
101
205
  });
102
206
  ```
103
207
 
104
- All loaders are resolved lazily; their fetch implementations are loaded only
105
- when needed. A custom loader can also use an in-memory dictionary or another
106
- data source:
208
+ Loader implementations are resolved lazily: `httpLoader` and `remoteLoader` are
209
+ separate chunks until first use. The default `jsonLoader` is part of the main
210
+ bundle — it runs in the app initializer, where a lazy chunk would put two extra
211
+ script requests between the main bundle and the dictionary fetch. A loader can
212
+ also be in-memory:
107
213
 
108
214
  ```ts
109
215
  import { customLoader } from '@rivinia/i18n';
110
216
 
111
- const inMemoryLoader = customLoader(async (language: 'en' | 'ar') => {
112
- const dictionaries = {
113
- en: { greeting: 'Hello' },
114
- ar: { greeting: 'مرحبًا' },
115
- };
116
- return dictionaries[language];
117
- });
217
+ const inMemory = customLoader(async (language: 'ar' | 'en') => ({
218
+ ar: { greeting: 'مرحبًا' },
219
+ en: { greeting: 'Hello' },
220
+ })[language]);
221
+ ```
222
+
223
+ A custom `TranslationLoader` receives the platform context:
224
+
225
+ ```ts
226
+ import type { LoaderDescriptor, LoaderContext, TranslationLoader } from '@rivinia/i18n';
227
+
228
+ const filesystem: LoaderDescriptor<'ar' | 'en'> = {
229
+ resolve: async (context?: LoaderContext): Promise<TranslationLoader<'ar' | 'en'>> => ({
230
+ load: async (language) =>
231
+ context?.isServer
232
+ ? JSON.parse(await readFile(`i18n/${language}.json`, 'utf8'))
233
+ : (await fetch(new URL(`i18n/${language}.json`, context?.baseUrl)).then((r) => r.json())),
234
+ }),
235
+ };
118
236
  ```
119
237
 
120
- Pass that descriptor as `loader: inMemoryLoader` in the provider config.
238
+ `LoaderContext.baseUrl` is an absolute, directory-like base (`document.baseURI` in the
239
+ browser; `<base href>` resolved against the request on the server). `isServer` means
240
+ "there is a server request context", which is what makes relative URLs fetchable.
241
+
242
+ ## Translation API
243
+
244
+ ### Signals
245
+
246
+ | Signal | Type | Meaning |
247
+ | ----------------------- | ----------------------------------- | -------------------------------------------------------------- |
248
+ | `currentLanguage` | `Signal<L>` | Active language id. |
249
+ | `currentLanguageObject` | `Signal<Language<L>>` | The active language entry. |
250
+ | `languageChanged` | `Signal<L>` | **Deprecated** — same signal as `currentLanguage`. |
251
+ | `languages` | `Signal<readonly Language<L>[]>` | Supported languages. |
252
+ | `dir` / `isRtl` | `Signal<Direction>` / `Signal<boolean>` | Document direction. |
253
+ | `locale` | `Signal<string>` | BCP-47 locale driving `Intl` and plural rules. |
254
+ | `loadingState` | `Signal<'idle' \| 'loading' \| 'error'>` | Current dictionary status. |
255
+ | `loadingError` | `Signal<unknown>` | Last load failure. |
256
+ | `isLoading` | `Signal<boolean>` | `loadingState() === 'loading'`. |
257
+ | `ready` | `Signal<boolean>` | Initial content settled — the one to gate skeletons on. |
258
+ | `loadedTranslations` | `Signal<Record<string, unknown>>` | The active dictionary. |
259
+ | `missingKeys` | `Signal<readonly string[]>` | Unresolved keys, insertion order, deduplicated. |
260
+
261
+ ### Methods
262
+
263
+ | Method | Result | Notes |
264
+ | --------------------------------------------- | --------------------- | --------------------------------------------------------------------- |
265
+ | `translate(key, params?)` | `string` | Key lookup + ICU rendering. |
266
+ | `translate(key, defaultValue, params?)` | `string` | A supplied `defaultValue` is not reported as missing. |
267
+ | `translate({ en: 'Hi', ar: 'أهلاً' })` | `string` | Inline map: current → fallback → first value. |
268
+ | `t(key, params?)` | `Signal<string>` | Same chain as a `computed`; params may be a function of signals. |
269
+ | `setLanguage(id)` / `setLanguageAsync(id)` | `void` / `Promise<void>` | Follows `switchStrategy`. |
270
+ | `toggle()` / `next()` / `previous()` | `void` | `toggle()` flips the first two languages (dev warning with more); `next()`/`previous()` cycle. |
271
+ | `loadTranslations(id, { silent? })` | `Promise<Record<…>>` | Preload without switching. |
272
+ | `reload(language?)` | `Promise<boolean>` | Invalidate + refetch; never rejects. |
273
+ | `formatNumber(value, options?)` | `string` | `Intl.NumberFormat` bound to `locale`. |
274
+ | `formatDate(value, options?)` | `string` | `Intl.DateTimeFormat` bound to `locale`. |
275
+ | `getLanguage(id)` | `Language<L> \| undefined` | Lookup. |
276
+ | `initialize()` | `Promise<void>` | Called by the provider; idempotent. |
277
+ | `clearMissingKeys()` | `void` | Reset the missing-key report. |
278
+ | `clearMissingParams()` | `void` | Reset the missing-parameter dedupe. |
279
+
280
+ `RTranslatePipe` (`rTranslate`) delegates to `translate()`. It is impure by necessity —
281
+ the service reads signals on every call — so prefer `t()` or component code for long
282
+ lists.
283
+
284
+ ## ICU messages
285
+
286
+ Supported subset (MF1): `{name}` interpolation, `{n, plural, …}` (with `offset:`),
287
+ `{n, selectordinal, …}`, `{x, select, …}`, `#`, `{n, number[, style]}`,
288
+ `{d, date[, style]}`, and nesting.
121
289
 
122
- ## Use in a standalone component
290
+ ```json
291
+ {
292
+ "items": "{count, plural, =0 {No items} one {# item} other {# items}}",
293
+ "guests": "{n, plural, offset:1 =0 {Nobody} =1 {Only you} one {You and # other} other {You and # others}}",
294
+ "place": "{rank, selectordinal, one {#st} two {#nd} few {#rd} other {#th}}",
295
+ "amount": "{value, number, ::currency/USD}",
296
+ "ratio": "{value, number, percent}",
297
+ "day": "{value, date, long}"
298
+ }
299
+ ```
123
300
 
124
- `provideRiviniaI18n()` registers an app initializer that loads the initial
125
- language before first paint. The `ready` signal becomes true when initial
126
- content is available or initial loading has settled; it is more useful for
127
- initial skeletons than `isLoading`.
301
+ - Categories come from `Intl.PluralRules(locale)`, so Arabic gets all six forms
302
+ (`zero`, `one`, `two`, `few`, `many`, `other`) with no dependency.
303
+ - `offset:` follows ICU: `=N` matches the **raw** value, the category is selected with
304
+ `value - offset`, and `#` renders `value - offset` in the locale's digits.
305
+ - `number` styles: `percent`, `integer`, `::currency/XXX`. `date` styles:
306
+ `short`/`medium`/`long`/`full`. Anything else is unsupported.
307
+ - Unsupported or malformed constructs never throw: the raw `{…}` segment is returned
308
+ as-is and parsing continues.
309
+ - `{name}` interpolation is `String(value)`; use `{n, number}` when formatting matters.
310
+ - `''` renders one apostrophe. A single apostrophe immediately before `{` or `}` (and
311
+ `#` inside a plural) starts a quoted literal that ends at the next apostrophe:
312
+ `It''s '{'x'}'` → `It's {x}`. A lone apostrophe elsewhere (`Don't`) is unchanged.
313
+ - `date` accepts a `Date`, epoch milliseconds, or a strict ISO-8601 string
314
+ (`2026-10-28`, `2026-10-28T12:00:00Z`). Invalid input keeps the raw segment. Plain
315
+ `{d}` on a `Date` uses `String()` — use `{d, date, …}` for localized output.
316
+ - Templates are compiled once into a cached AST, so a message rendered on every
317
+ change-detection pass is not re-parsed.
318
+
319
+ ## Missing keys
320
+
321
+ A key is missing only when it is absent from the current dictionary, absent from the
322
+ fallback dictionary, and no `defaultValue` was supplied. It is reported **once per key
323
+ per session**, and only once the current language actually has a dictionary — so a slow
324
+ load never produces false positives.
128
325
 
129
326
  ```ts
130
- // src/app/header.component.ts
131
- import { Component } from '@angular/core';
132
- import { RTranslatePipe } from '@rivinia/i18n';
133
- import { i18nConfig } from './i18n.config';
327
+ provideRiviniaI18n({
328
+ defaultLanguage: 'ar',
329
+ languages: […],
330
+ fallbackLanguage: 'en',
331
+ onMissingKey: ({ key, language, fallbackLanguage }) =>
332
+ report(key, { language, fallbackLanguage }),
333
+ });
334
+ ```
134
335
 
135
- @Component({
136
- selector: 'app-header',
137
- imports: [RTranslatePipe],
138
- templateUrl: './header.component.html',
139
- })
140
- export class HeaderComponent {
141
- readonly i18n = i18nConfig.inject();
142
- readonly seatCount = 3;
143
- readonly price = 12.5;
336
+ ```html
337
+ @if (i18n.missingKeys().length) {
338
+ <p role="status">{{ i18n.missingKeys().length }} untranslated keys</p>
144
339
  }
145
340
  ```
146
341
 
147
- ```html
148
- <!-- src/app/header.component.html -->
149
- @if (i18n.ready()) {
150
- <p>{{ i18n.translate({ en: 'Welcome', ar: 'أهلاً' }) }}</p>
151
- <p>{{ 'booking.seats' | rTranslate: { count: seatCount } }}</p>
152
- <p>{{ i18n.formatNumber(price, { style: 'currency', currency: 'USD' }) }}</p>
153
- <button type="button" (click)="i18n.setLanguage('ar')">العربية</button>
154
- <button type="button" (click)="i18n.setLanguage('en')">English</button>
155
- } @else {
156
- <p>Loading…</p>
342
+ Without `onMissingKey`, a `console.warn` is logged once per key in dev mode. Set
343
+ `warnOnMissingKey: false` to silence it, or `true` to keep it in production.
344
+
345
+ ## Missing parameters
346
+
347
+ A message that needs `{name}` but receives no `name` keeps the placeholder — it is
348
+ never replaced with `undefined`. Report it the same way as missing keys:
349
+
350
+ ```ts
351
+ provideRiviniaI18n({
352
+ // …
353
+ onMissingParam: ({ key, param, language }) => report(param, { key, language }),
354
+ });
355
+ ```
356
+
357
+ Without `onMissingParam`, dev mode logs one warning per (key, param) pair. Set
358
+ `warnOnMissingParam: false` to silence it. The hook is delivered from a microtask,
359
+ so it may write signals, and `i18n.clearMissingParams()` resets the dedupe.
360
+
361
+ ## Fallback language
362
+
363
+ Lookup order for `translate(key)`:
364
+
365
+ 1. current dictionary — rendered with the **current** locale;
366
+ 2. fallback dictionary — rendered with the **fallback** locale;
367
+ 3. `defaultValue` — current locale;
368
+ 4. the key itself.
369
+
370
+ Rule 2's locale is deliberate: an English plural template borrowed by an Arabic UI must
371
+ use English plural rules (2 categories), not Arabic (6).
372
+
373
+ The fallback dictionary loads in parallel with the initial language and **silently** — a
374
+ fallback failure reaches `onLoadError` but never sets `loadingState` to `'error'`, because
375
+ the current dictionary is what the UI needs. It is transferred with the rest of the state,
376
+ so hydration does not fetch it again. With `preload: false`, the fallback works from
377
+ cache/inline dictionaries only.
378
+
379
+ ## Reloading a dictionary
380
+
381
+ ```ts
382
+ await i18n.reload(); // current + fallback; drops every other cached language
383
+ await i18n.reload('en'); // one language; applied only if it is the current one
384
+ ```
385
+
386
+ `reload()` is stale-while-revalidate: the visible dictionary stays on screen until the
387
+ fresh one arrives, so a reload never flashes raw keys. Each language carries a generation
388
+ counter, so a response that was in flight when `reload()` ran is discarded instead of
389
+ overwriting the new one. It never rejects — failures land on `loadingState`,
390
+ `loadingError` and `onLoadError`.
391
+
392
+ A typical deploy hook:
393
+
394
+ ```ts
395
+ window.addEventListener('focus', () => void i18n.reload());
396
+ ```
397
+
398
+ ## `t()` signals
399
+
400
+ ```ts
401
+ readonly title = this.i18n.t('app.title');
402
+ readonly items = this.i18n.t('cart.items', () => ({ count: this.count() }));
403
+ ```
404
+
405
+ A function `params` is invoked inside the computation, so the signals it reads are
406
+ tracked: changing `count` re-renders the text without touching the language. `t()` is a
407
+ `computed` over the same resolution chain as `translate()`, and missing keys are recorded
408
+ in a microtask because Angular forbids signal writes inside a `computed`.
409
+
410
+ Use it for component fields. For a template expression that runs on every change
411
+ detection, `translate()` or the pipe is cheaper.
412
+
413
+ ## Typed keys
414
+
415
+ The registry is empty by default, so `RegisteredI18nKey` resolves to `string` and nothing
416
+ breaks. Generate the declaration from a dictionary to make a typo a compile error:
417
+
418
+ ```bash
419
+ npx rivinia-i18n-keys
420
+ # → src/i18n-keys.d.ts
421
+ npx rivinia-i18n-keys --source public/i18n/en.json --out src/i18n-keys.d.ts
422
+ npx rivinia-i18n-keys --check # exit 1 when the file is stale (CI)
423
+ npx rivinia-i18n-keys --parity --dir public/i18n --base en
424
+ ```
425
+
426
+ ```ts
427
+ // src/i18n-keys.d.ts — generated, do not edit
428
+ import '@rivinia/i18n';
429
+
430
+ declare module '@rivinia/i18n' {
431
+ interface RiviniaI18nKeyRegistry {
432
+ readonly keys: 'app.title' | 'app.save' | 'booking.seats';
433
+ }
157
434
  }
158
435
  ```
159
436
 
160
- For key lookup, `translate('booking.seats', { count: 3 })` is also available.
161
- Missing keys return the key itself, or the supplied fallback:
162
- `translate('missing.key', 'Not available')`. Inline language maps fall back to
163
- their first value if the active language is absent. `RTranslatePipe` is
164
- impure so it reevaluates when the language changes; for long lists, prefer
165
- calling `translate()` in component code.
166
-
167
- ## Loading, switching, and SSR
168
-
169
- - Initial language loading is enabled by default. Set `preload: false` to skip
170
- the initial request; the service then marks `ready()` true immediately.
171
- - `translations` can seed inline dictionaries before the initial request. A
172
- successful loader response replaces the seed; if loading fails, the seed
173
- remains visible. For an app with no network, pair inline translations with
174
- a `customLoader` or disable preloading as appropriate.
175
- - Load failures do not reject provider initialization. Inspect
176
- `loadingState()`/`loadingError()` or handle them with `onLoadError`; lookups
177
- still fall back to the key or supplied fallback.
178
- - `switchStrategy: 'instant'` changes language immediately and loads in the
179
- background. `'preload-first'` waits for the new dictionary; a failed load
180
- leaves the current language and direction unchanged. You can also call and
181
- await `setLanguageAsync(id)` explicitly.
182
- - `loadTranslations(id)` preloads a dictionary without switching. Dictionaries
183
- are cached by language; out-of-order responses do not replace the currently
184
- displayed language.
185
- - For SSR, dictionaries are transferred to the browser to avoid a second
186
- fetch. `storageStrategy: 'cookie'` reads the request cookie on the server
187
- and writes it in the browser, keeping the initial language consistent.
188
- Local/session storage are unavailable on the server and fall back to the
189
- configured default or browser detection.
190
-
191
- ## ICU messages and formatting
192
-
193
- The supported ICU subset is plain `{name}` interpolation, `{count, plural,
194
- ...}`, `{gender, select, ...}`, nested messages, exact numeric selectors such
195
- as `=0`, and `#` inside a plural. Selection follows the platform's plural
196
- rules for the configured locale; dictionaries can provide all six Arabic
197
- categories. This is not full ICU MessageFormat; date/time and number
198
- formatting are separate `formatDate()` and `formatNumber()` methods. Malformed
199
- or unsupported messages render as raw text rather than throwing.
200
-
201
- Set `locale` on a language entry when the language ID alone is not the desired
202
- formatting locale. For example, the Arabic-Egypt locale can request its
203
- appropriate digit conventions.
204
-
205
- ## Public API
206
-
207
- | Export | Kind | Purpose |
208
- | ----------------------------------------------------------------------------------------------------------------------------------------------- | ------------------ | -------------------------------------------------------------------------- |
209
- | `provideRiviniaI18n(config)` | Provider | Configure languages, loader, persistence, startup loading, and switching. |
210
- | `defineRiviniaI18n(config)` | Helper | Bind config and preserve the configured language union in `inject()`. |
211
- | `RiviniaI18n`, `injectRiviniaI18n()` | Service / function | Language, direction, loading, translation, switching, and formatting APIs. |
212
- | `RTranslatePipe` | Pipe | Template pipe named `rTranslate`. |
213
- | `jsonLoader`, `httpLoader`, `remoteLoader`, `customLoader` | Loaders | Lazy descriptors for fetch-based or custom dictionary loading. |
214
- | `formatIcu`, `detectBrowserLanguage`, `browserLanguages` | Utilities | Format the supported ICU subset; inspect browser language matches. |
215
- | `parseCookie`, `serializeCookie` | Utilities | Cookie strategy helpers. |
216
- | `ViewTransitionService` | Service | View-transition integration used by the optional config. |
217
- | `Language`, `Translation`, `TranslateParams`, `RiviniaI18nConfig`, `StorageStrategy`, `SwitchStrategy`, `LoaderDescriptor`, `TranslationLoader` | Types | Configuration, dictionary, and loader types. |
437
+ With that file in the program:
438
+
439
+ ```ts
440
+ i18n.translate('app.title'); // ok
441
+ i18n.t('app.titel'); // TS error: not assignable to 'app.title' | …
442
+ i18n.translate(`status.${code}` as RegisteredI18nKey); // dynamic key, explicit
443
+ ```
444
+
445
+ The CLI flattens nested objects to dot paths, keeps literal dotted keys as-is, keeps
446
+ string leaves only, warns about non-string leaves and key collisions (the flat key
447
+ wins), sorts keys for stable diffs, and escapes quotes. It has no dependencies and
448
+ ships with the package (`rivinia-i18n-keys`).
449
+
450
+ `--parity` compares every `<language>.json` in `--dir` against `--base` and reports,
451
+ sorted: keys missing from a language, keys extra to it, and ICU placeholders used by
452
+ the base string but absent from the translation. Placeholders inside plural/select
453
+ branches are compared too; branch text itself is never read as a parameter. Any
454
+ mismatch exits 1, so CI fails on the common "added to `en.json`, forgot `ar.json`" bug.
455
+
456
+ ## SSR
457
+
458
+ The default loader works on the server: `REQUEST` plus `<base href>` produce an absolute
459
+ URL, so Node's `fetch` never sees a relative path. The rendered dictionaries go into the
460
+ `TransferState`, and the browser reads them instead of fetching again.
461
+
462
+ - **A custom SSR host must provide `REQUEST`.** `renderApplication` does not add it;
463
+ `@angular/ssr` does. Without it the service cannot build an absolute URL on the server
464
+ and the default loader fails there — the same as any other library that needs the
465
+ request origin.
466
+ - **Provide the serializer in the app injector.** `renderApplication` serializes the
467
+ *platform* `TransferState`, while `bootstrapApplication` gives the app its own root
468
+ injector, so dictionaries loaded by the service land in a different instance. Register
469
+ a `BEFORE_APP_SERIALIZED` callback (or `provideServerRendering()`) in the app providers.
470
+ - **Serve the CSR shell as the template.** With `outputMode: 'server'` the builder
471
+ prerenders `browser/index.html`, so that file already contains a rendered app and its
472
+ own `ng-state` script. Use `browser/index.csr.html` as the render template; otherwise
473
+ the response carries two scripts with the same id and the client reads the empty one.
474
+ - `storageStrategy: 'cookie'` reads the request cookie on the server and writes it in the
475
+ browser, so the first paint matches the user's choice. Local/session storage fall back
476
+ to the default language or browser detection on the server.
477
+ - `provideClientHydration(withEventReplay())` is the standard client side; the clean CSR
478
+ shell carries no event-dispatch contract script, so an event fired before hydration
479
+ completes is not replayed.
480
+
481
+ A complete, runnable host lives in `projects/i18n-e2e` (`node:http` +
482
+ `renderApplication`, no Express), with `e2e/ssr-smoke.mjs` asserting the raw HTML, the
483
+ server log, the transfer payload, the absence of a client refetch, and hydration.
484
+
485
+ ## Migration: 0.3.3 → 0.4.0
486
+
487
+ Everything below is additive; no export was removed and no import path changed. Two
488
+ behaviour changes are worth reading:
489
+
490
+ 1. **`#` in a plural now uses the locale's digits.** It is formatted with
491
+ `Intl.NumberFormat(locale)` instead of the raw number, so a locale whose default
492
+ numbering system is not Latin (for example `ar-EG`) renders `٣` where it used to
493
+ render `3`. `en` and `ar` are unchanged.
494
+ 2. **Missing keys warn in dev mode.** A key that resolves to nothing now logs
495
+ `[rivinia/i18n] missing key "…"` once per session when `isDevMode()` is true. Set
496
+ `warnOnMissingKey: false`, or pass `onMissingKey`, to control it.
497
+
498
+ New in 0.4.0: `fallbackLanguage`, `onMissingKey`, `warnOnMissingKey`, `missingKeys`,
499
+ `clearMissingKeys()`, `reload()`, `t()`, the typed-key registry and the
500
+ `rivinia-i18n-keys` CLI, ICU `selectordinal`/`offset:`/`{n, number}`/`{d, date}`, and
501
+ `Date` in `TranslateParams`. The default loader is unchanged (`i18n/{language}.json`);
502
+ `jsonLoader({ path: 'assets/i18n' })` keeps the old layout. The internal source layout
503
+ moved (models/services/utils/providers/pipes) but nothing under `src/` was ever
504
+ exported.
218
505
 
219
506
  ## License
220
507