@rivinia/i18n 0.2.0 → 0.3.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 CHANGED
@@ -3,124 +3,216 @@
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
- Headless language manager for Angular 22+. Signals, RTL/LTR, lazy loaders,
7
- ICU plurals (all six Arabic forms), browser detection, Intl formatting —
8
- zero DOM opinions beyond `<html dir/lang>`, zero styling.
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.
9
10
 
10
- - Version: **0.2.0**
11
- - Requires: **Angular `^22.0.0`**, `tslib`
11
+ - Prepared patch: **0.3.1** (latest published: **0.3.0**)
12
+ - Peer dependency: **`@angular/core` `^22.0.0`**
13
+ - No `tslib` or `HttpClient` peer dependency. Built-in loaders use `fetch`.
12
14
 
13
- ## Install
15
+ ## Install and configure
14
16
 
15
17
  ```bash
16
18
  npm install @rivinia/i18n
17
- ng add @rivinia/i18n # asks default language + browser detection, wires an ar/en starter
19
+ ng add @rivinia/i18n
18
20
  ```
19
21
 
20
- ## Dictionaries by convention (no config needed)
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:
21
25
 
22
- Key-based `translate('booking.seats')` works out of the box with the conventional
23
- layout — the default loader fetches `assets/i18n/{language}.json`
24
- (`assets/i18n/ar.json`, `assets/i18n/en.json`, …). Override only when you differ:
25
-
26
- ```json
27
- // src/assets/i18n/ar.json
28
- { "booking": { "seats": "{count, plural, zero {لا مقاعد} one {مقعد واحد} other {# مقاعد}}" } }
26
+ ```ts
27
+ // src/app/i18n.config.ts
28
+ import { defineRiviniaI18n, jsonLoader } from '@rivinia/i18n';
29
+
30
+ export const i18nConfig = defineRiviniaI18n({
31
+ defaultLanguage: 'en',
32
+ languages: [
33
+ { id: 'en', nativeName: 'English', dir: 'ltr', locale: 'en-US' },
34
+ { id: 'ar', nativeName: 'العربية', dir: 'rtl', locale: 'ar-EG' },
35
+ ],
36
+ detectBrowser: true,
37
+ switchStrategy: 'preload-first',
38
+ loader: jsonLoader(),
39
+ });
29
40
  ```
30
41
 
31
42
  ```ts
32
- // custom path / HTTP endpoint / in-memory (first truth wins):
33
- provideRiviniaI18n({ loader: jsonLoader({ path: '/my-i18n' }), ... });
34
- provideRiviniaI18n({ loader: httpLoader({ endpoint: 'https://api.example.com/i18n' }), ... });
35
- // inline-only apps (zero network): loader: customLoader(async () => ({}))
43
+ // src/app/app.config.ts
44
+ import type { ApplicationConfig } from '@angular/core';
45
+ import { i18nConfig } from './i18n.config';
46
+
47
+ export const appConfig: ApplicationConfig = {
48
+ providers: [i18nConfig.provide()],
49
+ };
36
50
  ```
37
51
 
38
- Loaders code-split: fetch implementations load on first use only.
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.
39
56
 
40
- ## Startup loading (no raw keys on first paint)
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.
41
61
 
42
- `provideRiviniaI18n()` registers an app initializer that loads the initial
43
- language before first paint (SSR waits via `PendingTasks`):
62
+ ## Dictionaries
44
63
 
45
- ```ts
46
- provideRiviniaI18n({
47
- // ...
48
- preload: false, // opt out: load manually instead
49
- translations: { ar: { hello: 'مرحبا' } }, // inline seed: instant, zero network,
50
- }); // a successful loader response still wins
51
- ```
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`.
68
+
69
+ If an existing app still serves dictionaries from `assets/i18n/`, keep that
70
+ layout with `jsonLoader({ path: 'assets/i18n' })` instead.
52
71
 
53
- Gate skeletons on the `ready` signal (true once initial content is available),
54
- not on `isLoading`. Load failures never reject setup — they land on
55
- `loadingError`/`onLoadError` with safe fallbacks preserved.
72
+ ```json
73
+ // public/i18n/en.json
74
+ {
75
+ "booking": {
76
+ "seats": "{count, plural, =0 {No seats} one {# seat} other {# seats}}"
77
+ }
78
+ }
79
+ ```
56
80
 
57
- ## Persistence and SSR
81
+ ```json
82
+ // public/i18n/ar.json
83
+ {
84
+ "booking": {
85
+ "seats": "{count, plural, zero {لا مقاعد} one {مقعد واحد} two {مقعدان} few {# مقاعد} many {# مقعدًا} other {# مقعد}}"
86
+ }
87
+ }
88
+ ```
58
89
 
59
- - `storageStrategy: 'cookie'` syncs SSR and browser through one cookie:
60
- the server reads the request cookie (correct first paint, no hydration
61
- mismatch), the browser writes it. `local`/`session` fall back to the
62
- default language on the server.
63
- - Dictionaries loaded on the server travel to the browser via `TransferState`
64
- (no double fetch). The `<html dir/lang>` effect uses injected `DOCUMENT`,
65
- so it renders on the server too.
90
+ The default loader does not use `HttpClient`. To use a different JSON path or
91
+ an endpoint, pass a loader descriptor:
66
92
 
67
93
  ```ts
68
- // app.config.ts
69
- import { provideRiviniaI18n } from '@rivinia/i18n';
70
-
71
- providers: [
72
- provideRiviniaI18n({
73
- defaultLanguage: 'ar',
74
- languages: [
75
- { id: 'ar', nativeName: 'العربية', dir: 'rtl' },
76
- { id: 'en', nativeName: 'English', dir: 'ltr' },
77
- ],
78
- }),
79
- ];
94
+ import { httpLoader, jsonLoader, remoteLoader } from '@rivinia/i18n';
95
+
96
+ jsonLoader({ path: '/my-i18n' }); // fetches /my-i18n/{language}.json
97
+ httpLoader({ endpoint: 'https://api.example.com/i18n' }); // appends /{language}
98
+ remoteLoader({
99
+ url: (language) => `https://api.example.com/v2/${language}`,
100
+ headers: { Authorization: 'Bearer …' },
101
+ });
80
102
  ```
81
103
 
82
- ## Quick start
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:
83
107
 
84
108
  ```ts
85
- export class Header {
86
- i18n = injectRiviniaI18n();
87
- save = () => this.i18n.translate({ ar: 'حفظ', en: 'Save' });
88
- seats = (n: number) => this.i18n.translate('booking.seats', { count: n });
89
- }
109
+ import { customLoader } from '@rivinia/i18n';
110
+
111
+ const inMemoryLoader = customLoader(async (language: 'en' | 'ar') => {
112
+ const dictionaries = {
113
+ en: { greeting: 'Hello' },
114
+ ar: { greeting: 'مرحبًا' },
115
+ };
116
+ return dictionaries[language];
117
+ });
90
118
  ```
91
119
 
92
- ```json
93
- // assets/i18n/en.json
94
- { "booking": { "seats": "{count, plural, one {# seat} other {# seats}}" } }
95
- ```
120
+ Pass that descriptor as `loader: inMemoryLoader` in the provider config.
96
121
 
97
- ```html
98
- <p>{{ i18n.translate({ ar: 'مرحبا', en: 'Hello' }) }}</p>
99
- <p>{{ 'booking.seats' | rTranslate:{ count: seats() } }}</p>
122
+ ## Use in a standalone component
123
+
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`.
128
+
129
+ ```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';
134
+
135
+ @Component({
136
+ selector: 'app-header',
137
+ standalone: true,
138
+ imports: [RTranslatePipe],
139
+ template: `
140
+ @if (i18n.ready()) {
141
+ <p>{{ i18n.translate({ en: 'Welcome', ar: 'أهلاً' }) }}</p>
142
+ <p>{{ 'booking.seats' | rTranslate: { count: seatCount } }}</p>
143
+ <p>{{ i18n.formatNumber(price, { style: 'currency', currency: 'USD' }) }}</p>
144
+ <button type="button" (click)="i18n.setLanguage('ar')">العربية</button>
145
+ <button type="button" (click)="i18n.setLanguage('en')">English</button>
146
+ } @else {
147
+ <p>Loading…</p>
148
+ }
149
+ `,
150
+ })
151
+ export class HeaderComponent {
152
+ readonly i18n = i18nConfig.inject();
153
+ readonly seatCount = 3;
154
+ readonly price = 12.5;
155
+ }
100
156
  ```
101
157
 
102
- ## API
103
-
104
- | Export | Kind | Purpose |
105
- |---|---|---|
106
- | `provideRiviniaI18n(config)` | provider | languages, default, storage (+`cookie`), loader, `detectBrowser?` (off), `switchStrategy?`, `preload?`, `translations?` (inline seed) |
107
- | `RiviniaI18n` | `@Service()` | signals (`locale`, `ready`) + `translate/setLanguage(toggle/next/previous)/loadTranslations/formatNumber/formatDate` |
108
- | `injectRiviniaI18n()` | function | shorthand, preserves the language union; `defineRiviniaI18n(config)` binds config + accessors with inference |
109
- | `jsonLoader/httpLoader/remoteLoader/customLoader` | loaders | lazy code-split dictionaries (fetch, no HttpClient) |
110
- | `formatIcu(template, params, locale)` | util | ICU subset: plural/select/`#`/nesting via native `Intl.PluralRules` |
111
- | `detectBrowserLanguage(ids, langs)` | util | in-order priority + base-tag fallback (`ar-EG` → `ar`), pure/testable |
112
- | `parseCookie/serializeCookie` | utils | cookie strategy primitives (server header / browser cookie) |
113
- | `RTranslatePipe` | pipe | `rTranslate` (impure by necessity — prefer `translate()` in code for lists) |
114
- | types | types | `RiviniaI18nConfig`, `Language` (+`locale?`), `Translation`, `LoaderDescriptor`, … |
115
-
116
- Dictionaries commit to visible signals only for the currently intended
117
- language — out-of-order responses stay cached. `setLanguageAsync` aborts on
118
- load failure (language, direction and dictionary untouched). ICU subset is
119
- deliberately small (`plural`/`select` only) — full ICU belongs to
120
- FormatJS, not to a 10 kB core. Malformed templates render raw, never throw.
121
- Stored preference always beats browser detection; detection runs only when
122
- nothing is stored. `switchStrategy: 'preload-first'` (or `setLanguageAsync`)
123
- avoids raw-key flashes on route switches.
158
+ For key lookup, `translate('booking.seats', { count: 3 })` is also available.
159
+ Missing keys return the key itself, or the supplied fallback:
160
+ `translate('missing.key', 'Not available')`. Inline language maps fall back to
161
+ their first value if the active language is absent. `RTranslatePipe` is
162
+ impure so it reevaluates when the language changes; for long lists, prefer
163
+ calling `translate()` in component code.
164
+
165
+ ## Loading, switching, and SSR
166
+
167
+ - Initial language loading is enabled by default. Set `preload: false` to skip
168
+ the initial request; the service then marks `ready()` true immediately.
169
+ - `translations` can seed inline dictionaries before the initial request. A
170
+ successful loader response replaces the seed; if loading fails, the seed
171
+ remains visible. For an app with no network, pair inline translations with
172
+ a `customLoader` or disable preloading as appropriate.
173
+ - Load failures do not reject provider initialization. Inspect
174
+ `loadingState()`/`loadingError()` or handle them with `onLoadError`; lookups
175
+ still fall back to the key or supplied fallback.
176
+ - `switchStrategy: 'instant'` changes language immediately and loads in the
177
+ background. `'preload-first'` waits for the new dictionary; a failed load
178
+ leaves the current language and direction unchanged. You can also call and
179
+ await `setLanguageAsync(id)` explicitly.
180
+ - `loadTranslations(id)` preloads a dictionary without switching. Dictionaries
181
+ are cached by language; out-of-order responses do not replace the currently
182
+ displayed language.
183
+ - For SSR, dictionaries are transferred to the browser to avoid a second
184
+ fetch. `storageStrategy: 'cookie'` reads the request cookie on the server
185
+ and writes it in the browser, keeping the initial language consistent.
186
+ Local/session storage are unavailable on the server and fall back to the
187
+ configured default or browser detection.
188
+
189
+ ## ICU messages and formatting
190
+
191
+ The supported ICU subset is plain `{name}` interpolation, `{count, plural,
192
+ ...}`, `{gender, select, ...}`, nested messages, exact numeric selectors such
193
+ as `=0`, and `#` inside a plural. Selection follows the platform's plural
194
+ rules for the configured locale; dictionaries can provide all six Arabic
195
+ categories. This is not full ICU MessageFormat; date/time and number
196
+ formatting are separate `formatDate()` and `formatNumber()` methods. Malformed
197
+ or unsupported messages render as raw text rather than throwing.
198
+
199
+ Set `locale` on a language entry when the language ID alone is not the desired
200
+ formatting locale. For example, the Arabic-Egypt locale can request its
201
+ appropriate digit conventions.
202
+
203
+ ## Public API
204
+
205
+ | Export | Kind | Purpose |
206
+ | ----------------------------------------------------------------------------------------------------------------------------------------------- | ------------------ | -------------------------------------------------------------------------- |
207
+ | `provideRiviniaI18n(config)` | Provider | Configure languages, loader, persistence, startup loading, and switching. |
208
+ | `defineRiviniaI18n(config)` | Helper | Bind config and preserve the configured language union in `inject()`. |
209
+ | `RiviniaI18n`, `injectRiviniaI18n()` | Service / function | Language, direction, loading, translation, switching, and formatting APIs. |
210
+ | `RTranslatePipe` | Pipe | Template pipe named `rTranslate`. |
211
+ | `jsonLoader`, `httpLoader`, `remoteLoader`, `customLoader` | Loaders | Lazy descriptors for fetch-based or custom dictionary loading. |
212
+ | `formatIcu`, `detectBrowserLanguage`, `browserLanguages` | Utilities | Format the supported ICU subset; inspect browser language matches. |
213
+ | `parseCookie`, `serializeCookie` | Utilities | Cookie strategy helpers. |
214
+ | `ViewTransitionService` | Service | View-transition integration used by the optional config. |
215
+ | `Language`, `Translation`, `TranslateParams`, `RiviniaI18nConfig`, `StorageStrategy`, `SwitchStrategy`, `LoaderDescriptor`, `TranslationLoader` | Types | Configuration, dictionary, and loader types. |
124
216
 
125
217
  ## License
126
218
 
@@ -1,4 +1,4 @@
1
- const DEFAULT_BASE_PATH = "assets/i18n";
1
+ const DEFAULT_BASE_PATH = "i18n";
2
2
  var JsonLoader = class {
3
3
  _options;
4
4
  constructor(_options) {
@@ -13,4 +13,4 @@ var JsonLoader = class {
13
13
  };
14
14
  export { JsonLoader };
15
15
 
16
- //# sourceMappingURL=rivinia-i18n-json-loader.impl-CGzkWfF_.mjs.map
16
+ //# sourceMappingURL=rivinia-i18n-json-loader.impl-VXwAmyWL.mjs.map
@@ -0,0 +1 @@
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"}
@@ -2,7 +2,7 @@ import * as i0 from "@angular/core";
2
2
  import { DOCUMENT, InjectionToken, PendingTasks, Pipe, REQUEST, Service, TransferState, computed, effect, inject, makeEnvironmentProviders, makeStateKey, provideAppInitializer, signal } from "@angular/core";
3
3
  function jsonLoader(options) {
4
4
  return { async resolve() {
5
- const { JsonLoader } = await import("./rivinia-i18n-json-loader.impl-CGzkWfF_.mjs");
5
+ const { JsonLoader } = await import("./rivinia-i18n-json-loader.impl-VXwAmyWL.mjs");
6
6
  return new JsonLoader(options);
7
7
  } };
8
8
  }
@@ -86,8 +86,19 @@ function parseCookie(header, name) {
86
86
  }
87
87
  return null;
88
88
  }
89
- function serializeCookie(name, value) {
90
- return `${name}=${encodeURIComponent(value)}; Path=/; Max-Age=31536000; SameSite=Lax`;
89
+ function serializeCookie(name, value, options) {
90
+ const base = `${name}=${encodeURIComponent(value)}; Path=/; Max-Age=31536000; SameSite=Lax`;
91
+ return options?.secure ? `${base}; Secure` : base;
92
+ }
93
+ function shouldSecureCookie(location) {
94
+ try {
95
+ if (!location) return false;
96
+ if (location.protocol !== "https:") return false;
97
+ if (location.hostname === "localhost") return false;
98
+ return true;
99
+ } catch {
100
+ return false;
101
+ }
91
102
  }
92
103
  function formatIcu(template, params, locale) {
93
104
  return parseMessage(template, 0, template.length, params, locale, null).text;
@@ -278,13 +289,6 @@ function readSelector(src, i, end) {
278
289
  const RIVINIA_I18N_CONFIG = new InjectionToken("RIVINIA_I18N_CONFIG");
279
290
  var ViewTransitionService = class ViewTransitionService {
280
291
  _doc = inject(DOCUMENT);
281
- get _supported() {
282
- try {
283
- return typeof this._doc.startViewTransition === "function";
284
- } catch {
285
- return false;
286
- }
287
- }
288
292
  run(callback) {
289
293
  const doc = this._doc;
290
294
  if (typeof doc.startViewTransition === "function") doc.startViewTransition(callback);
@@ -547,7 +551,8 @@ var RiviniaI18n = class RiviniaI18n {
547
551
  if (this._storageStrategy === "cookie") {
548
552
  if (this._request) return;
549
553
  try {
550
- this._doc.cookie = serializeCookie(this._storageKey, id);
554
+ const location = this._doc?.location;
555
+ this._doc.cookie = serializeCookie(this._storageKey, id, { secure: shouldSecureCookie(location) });
551
556
  } catch {}
552
557
  return;
553
558
  }
@@ -663,7 +668,6 @@ i0.ɵɵngDeclareClassMetadata({
663
668
  type: Pipe,
664
669
  args: [{
665
670
  name: "rTranslate",
666
- standalone: true,
667
671
  pure: false
668
672
  }]
669
673
  }]
@@ -1 +1 @@
1
- {"version":3,"file":"rivinia-i18n.mjs","names":[],"sources":["../../../projects/i18n/src/lib/loaders.ts","../../../projects/i18n/src/lib/i18n-utils.ts","../../../projects/i18n/src/lib/cookies.ts","../../../projects/i18n/src/lib/icu.ts","../../../projects/i18n/src/lib/i18n-config.ts","../../../projects/i18n/src/lib/view-transition.service.ts","../../../projects/i18n/src/lib/rivinia-i18n.ts","../../../projects/i18n/src/lib/provide-i18n.ts","../../../projects/i18n/src/lib/translate.pipe.ts"],"sourcesContent":["/**\n * Pluggable key-dictionary loader. Returns a flat/nested JSON-compatible map\n * merged into `loadedTranslations` and read by key-based `translate(key)`.\n */\nexport interface TranslationLoader<L extends string = string> {\n load(language: L): Promise<Record<string, unknown>>;\n}\n\n/**\n * Lazy descriptor: `resolve()` dynamic-imports the real implementation, so\n * loader code splits out of the main bundle until first use. Resolved once\n * and cached by the service.\n */\nexport interface LoaderDescriptor<L extends string = string> {\n resolve(): Promise<TranslationLoader<L>>;\n}\n\nexport function jsonLoader(options?: { path?: string }): LoaderDescriptor<string> {\n return {\n async resolve() {\n const { JsonLoader } = await import('./json-loader.impl');\n return new JsonLoader(options);\n },\n };\n}\n\nexport interface HttpLoaderOptions {\n readonly endpoint: string;\n readonly method?: string;\n readonly buildUrl?: (language: string) => string;\n}\n\nexport function httpLoader(options: HttpLoaderOptions): LoaderDescriptor<string> {\n return {\n async resolve() {\n const { HttpLoader } = await import('./http-loader.impl');\n return new HttpLoader(options);\n },\n };\n}\n\nexport interface RemoteLoaderOptions {\n readonly url: (language: string) => string;\n readonly headers?: Record<string, string>;\n}\n\nexport function remoteLoader(options: RemoteLoaderOptions): LoaderDescriptor<string> {\n return {\n async resolve() {\n const { RemoteLoader } = await import('./remote-loader.impl');\n return new RemoteLoader(options);\n },\n };\n}\n\n/** Wraps any function as a loader (mocks, in-memory, third-party SDKs). */\nexport function customLoader<L extends string = string>(\n load: (language: L) => Promise<Record<string, unknown>>,\n): LoaderDescriptor<L> {\n return {\n async resolve() {\n return { load };\n },\n };\n}\n","import type { StorageStrategy } from './i18n-types';\n\nfunction getStorage(strategy: StorageStrategy): Storage | null {\n // NOTE: 'cookie' resolves to null on purpose — cookies need request/document\n // context, so the service handles that strategy itself (server REQUEST\n // header, browser document.cookie). See RiviniaI18n storage methods.\n if (strategy === 'none' || strategy === 'cookie') return null;\n if (typeof window === 'undefined') return null;\n try {\n return strategy === 'session' ? window.sessionStorage : window.localStorage;\n } catch {\n return null;\n }\n}\n\n/** SSR-safe read. Returns `null` off-browser, on denial, or when missing. */\nexport function safeGetItem(key: string, strategy: StorageStrategy): string | null {\n const storage = getStorage(strategy);\n if (!storage) return null;\n try {\n return storage.getItem(key);\n } catch {\n return null;\n }\n}\n\n/** SSR-safe write. Silently no-ops off-browser or on denial. */\nexport function safeSetItem(key: string, value: string, strategy: StorageStrategy): void {\n const storage = getStorage(strategy);\n if (!storage) return;\n try {\n storage.setItem(key, value);\n } catch {\n // Intentionally silent: persistence is best-effort.\n }\n}\n\n/**\n * Matches the browser language priority list against supported ids, in order.\n * For each browser entry (highest preference first) tries the exact tag, then\n * its base subtag (`ar-EG` → `ar`). Returns the first hit, or `null`.\n * Pure and exported for testing — pass `navigator.languages` in app code.\n */\nexport function detectBrowserLanguage<T extends string>(\n supportedIds: readonly T[],\n browserLanguages: readonly string[] | undefined,\n): T | null {\n if (!browserLanguages || browserLanguages.length === 0) return null;\n const supported = supportedIds.map((id) => id.toLowerCase());\n for (const raw of browserLanguages) {\n const tag = raw.trim().toLowerCase();\n if (!tag) continue;\n const exact = supported.indexOf(tag);\n if (exact !== -1) return supportedIds[exact];\n const base = tag.split(/[-_]/)[0];\n if (base && base !== tag) {\n const hit = supported.indexOf(base);\n if (hit !== -1) return supportedIds[hit];\n }\n }\n return null;\n}\n\n/** Browser language list, `undefined` off-browser (SSR-safe input for detection). */\nexport function browserLanguages(): readonly string[] | undefined {\n if (typeof window === 'undefined' || typeof navigator === 'undefined') return undefined;\n try {\n if (Array.isArray(navigator.languages) && navigator.languages.length > 0) {\n return [...navigator.languages];\n }\n return typeof navigator.language === 'string' ? [navigator.language] : undefined;\n } catch {\n return undefined;\n }\n}\n","/**\n * Cookie helpers for the `'cookie'` storage strategy. Pure and SSR-testable:\n * the service supplies the header (server `REQUEST`) or `document.cookie`\n * (browser); these functions only parse and serialize.\n */\n\n/** Extracts a cookie value by name from a `Cookie` header or `document.cookie`. */\nexport function parseCookie(\n header: string | null | undefined,\n name: string,\n): string | null {\n if (!header) return null;\n const prefix = `${name}=`;\n for (const part of header.split(';')) {\n const trimmed = part.trim();\n if (trimmed.startsWith(prefix)) {\n try {\n return decodeURIComponent(trimmed.slice(prefix.length));\n } catch {\n return trimmed.slice(prefix.length);\n }\n }\n }\n return null;\n}\n\n/** Serializes a language cookie ( Lax, root path, one year). */\nexport function serializeCookie(name: string, value: string): string {\n return `${name}=${encodeURIComponent(value)}; Path=/; Max-Age=31536000; SameSite=Lax`;\n}\n","import type { TranslateParams } from './i18n-types';\n\n/**\n * Minimal ICU MessageFormat subset: `{name}` interpolation, `{n, plural, …}`,\n * `{x, select, …}`, `#` inside plurals, and nesting. Categories resolve via\n * the native `Intl.PluralRules(locale)` — Arabic gets all six forms\n * (zero/one/two/few/many/other) with zero extra dependencies.\n *\n * Supported (and ONLY these — documented subset, translators beware):\n * - `{count, plural, =0 {none} one {# item} other {# items}}`\n * - `{gender, select, male {He} female {She} other {They}}`\n * - `{name}` plain interpolation (missing params keep the placeholder)\n *\n * Malformed input never throws: the raw segment is returned as-is.\n */\nexport function formatIcu(\n template: string,\n params: TranslateParams,\n locale: string,\n): string {\n return parseMessage(template, 0, template.length, params, locale, null).text;\n}\n\ninterface Parsed {\n text: string;\n /** Index of the closing `}` (or `end` when the level ran out). */\n next: number;\n ok: boolean;\n}\n\nfunction parseMessage(\n src: string,\n start: number,\n end: number,\n params: TranslateParams,\n locale: string,\n pluralValue: number | null,\n): Parsed {\n let out = '';\n let i = start;\n while (i < end) {\n const ch = src[i];\n if (ch === '{') {\n const arg = parseArgument(src, i, end, params, locale, pluralValue);\n if (!arg.ok) return { text: out + src.slice(i, end), next: end, ok: true };\n out += arg.text;\n i = arg.next;\n } else if (ch === '}') {\n return { text: out, next: i, ok: true };\n } else if (ch === '#' && pluralValue !== null) {\n out += String(pluralValue);\n i++;\n } else {\n out += ch;\n i++;\n }\n }\n return { text: out, next: i, ok: true };\n}\n\nfunction parseArgument(\n src: string,\n start: number,\n end: number,\n params: TranslateParams,\n locale: string,\n outerPlural: number | null,\n): Parsed {\n let i = skipSpaces(src, start + 1, end);\n const name = readWord(src, i, end);\n i = skipSpaces(src, name.next, end);\n if (i >= end) return { text: src.slice(start, end), next: end, ok: true };\n if (src[i] === '}') {\n const value = params[name.word];\n const rendered =\n value === undefined || value === null || name.word === ''\n ? src.slice(start, i + 1)\n : String(value);\n return { text: rendered, next: i + 1, ok: true };\n }\n if (src[i] !== ',' || name.word === '') {\n return { text: src.slice(start, end), next: end, ok: true };\n }\n i = skipSpaces(src, i + 1, end);\n const type = readWord(src, i, end);\n i = skipSpaces(src, type.next, end);\n if (i >= end || src[i] !== ',') return { text: src.slice(start, end), next: end, ok: true };\n if (type.word !== 'plural' && type.word !== 'select') {\n return { text: src.slice(start, end), next: end, ok: true };\n }\n i++;\n const numeric =\n type.word === 'plural' ? toFiniteNumber(params[name.word]) : null;\n const branches = new Map<string, string>();\n i = skipSpaces(src, i, end);\n let closed = false;\n while (i < end) {\n i = skipSpaces(src, i, end);\n if (i < end && src[i] === '}') {\n closed = true;\n break;\n }\n const sel = readSelector(src, i, end);\n if (sel.selector === null) return { text: src.slice(start, end), next: end, ok: true };\n i = skipSpaces(src, sel.next, end);\n if (i >= end || src[i] !== '{') {\n return { text: src.slice(start, end), next: end, ok: true };\n }\n // Bodies render immediately: '#' binds to THIS plural's number, or to an\n // outer plural when nested (select inherits, nested plural overrides).\n const body = parseMessage(\n src,\n i + 1,\n end,\n params,\n locale,\n numeric ?? outerPlural,\n );\n branches.set(sel.selector, body.text);\n i = body.next + 1;\n }\n if (!closed) return { text: src.slice(start, end), next: end, ok: true };\n if (type.word === 'select') {\n const raw = params[name.word];\n const key = raw === undefined || raw === null ? '' : String(raw);\n return { text: branches.get(key) ?? branches.get('other') ?? '', next: i + 1, ok: true };\n }\n if (numeric === null) return { text: branches.get('other') ?? '', next: i + 1, ok: true };\n const exact = branches.get(`=${numeric}`);\n if (exact !== undefined) return { text: exact, next: i + 1, ok: true };\n let category: string;\n try {\n category = new Intl.PluralRules(locale).select(numeric);\n } catch {\n category = 'other';\n }\n return { text: branches.get(category) ?? branches.get('other') ?? '', next: i + 1, ok: true };\n}\n\nfunction toFiniteNumber(value: string | number | boolean | undefined): number | null {\n if (typeof value === 'number') return Number.isFinite(value) ? value : null;\n if (typeof value === 'string' && value.trim() !== '') {\n const n = Number(value);\n return Number.isFinite(n) ? n : null;\n }\n return null;\n}\n\nfunction skipSpaces(src: string, i: number, end: number): number {\n while (i < end && /\\s/.test(src[i])) i++;\n return i;\n}\n\nfunction readWord(src: string, i: number, end: number): { word: string; next: number } {\n const start = skipSpaces(src, i, end);\n let j = start;\n while (j < end && /[^\\s,}]+/.test(src[j])) j++;\n return { word: src.slice(start, j), next: j };\n}\n\nfunction readSelector(\n src: string,\n i: number,\n end: number,\n): { selector: string | null; next: number } {\n i = skipSpaces(src, i, end);\n if (i < end && src[i] === '=') {\n let j = i + 1;\n if (j < end && src[j] === '-') j++;\n const digits = j;\n while (j < end && /[0-9]/.test(src[j])) j++;\n if (j < end && src[j] === '.' && j + 1 < end && /[0-9]/.test(src[j + 1])) {\n j++;\n while (j < end && /[0-9]/.test(src[j])) j++;\n }\n if (j === digits) return { selector: null, next: i };\n return { selector: src.slice(i, j), next: j };\n }\n const word = readWord(src, i, end);\n if (!word.word) return { selector: null, next: i };\n return { selector: word.word, next: word.next };\n}\n","import { InjectionToken } from '@angular/core';\nimport type {\n Language,\n StorageStrategy,\n SwitchStrategy,\n ViewTransitionConfig,\n} from './i18n-types';\nimport type { LoaderDescriptor } from './loaders';\n\n/**\n * Global configuration for `@rivinia/i18n`.\n */\nexport interface RiviniaI18nConfig<T extends string = string> {\n readonly languages: readonly Language<T>[];\n readonly defaultLanguage: T;\n readonly storageKey?: string;\n readonly storageStrategy?: StorageStrategy;\n readonly autoApplyDirection?: boolean;\n readonly viewTransition?: ViewTransitionConfig;\n /**\n * Dictionary source. Defaults to `jsonLoader()` — the conventional\n * `assets/i18n/{language}.json` layout. Override with any descriptor\n * (custom path, HTTP endpoint, in-memory). Inline-only apps that want zero\n * network traffic pass `customLoader(async () => ({}))`.\n */\n readonly loader?: LoaderDescriptor<T>;\n readonly switchStrategy?: SwitchStrategy;\n /** Called when a dictionary load fails. The service still falls back safely. */\n readonly onLoadError?: (language: T, error: unknown) => void;\n /**\n * Load the initial language during provider setup (before first paint).\n * SSR waits via `PendingTasks`. Set `false` to skip (e.g. fully inline apps\n * that call `loadTranslations` themselves).\n * @default true\n */\n readonly preload?: boolean;\n /**\n * Inline per-language dictionaries. Seeded before any network load (zero\n * network + SSR-safe first paint); a successful loader response still wins.\n */\n readonly translations?: Partial<Record<T, Record<string, unknown>>>;\n /**\n * Match `navigator.languages` against supported ids on first visit\n * (stored preference always wins; base tags match, e.g. `ar-EG` → `ar`).\n * @default false — explicit opt-in, no surprises.\n */\n readonly detectBrowser?: boolean;\n}\n\n/**\n * Internal configuration token. Consumers must use `provideRiviniaI18n()`.\n * @internal\n */\nexport const RIVINIA_I18N_CONFIG = new InjectionToken<RiviniaI18nConfig>(\n 'RIVINIA_I18N_CONFIG',\n);\n\nexport const DEFAULT_STORAGE_KEY = 'rivinia.i18n.language';\nexport const DEFAULT_STORAGE_STRATEGY: StorageStrategy = 'local';\nexport const DEFAULT_AUTO_APPLY_DIRECTION = true;\n","import { DOCUMENT, Service, inject } from '@angular/core';\n\n/** Progressive-enhancement wrapper around the View Transition API. */\n@Service()\nexport class ViewTransitionService {\n private readonly _doc = inject(DOCUMENT);\n\n private get _supported(): boolean {\n try {\n const doc = this._doc as Document & {\n startViewTransition?: (callback: () => void) => unknown;\n };\n return typeof doc.startViewTransition === 'function';\n } catch {\n return false;\n }\n }\n\n run(callback: () => void): void {\n const doc = this._doc as Document & {\n startViewTransition?: (callback: () => void) => unknown;\n };\n if (typeof doc.startViewTransition === 'function') {\n doc.startViewTransition(callback);\n } else {\n callback();\n }\n }\n}\n","import {\n DOCUMENT,\n PendingTasks,\n REQUEST,\n Service,\n TransferState,\n computed,\n effect,\n inject,\n makeStateKey,\n signal,\n type StateKey,\n} from '@angular/core';\nimport {\n DEFAULT_AUTO_APPLY_DIRECTION,\n DEFAULT_STORAGE_KEY,\n DEFAULT_STORAGE_STRATEGY,\n RIVINIA_I18N_CONFIG,\n type RiviniaI18nConfig,\n} from './i18n-config';\nimport type { Direction } from './i18n-types';\nimport type { Language } from './i18n-types';\nimport type { StorageStrategy } from './i18n-types';\nimport type { TranslateParams } from './i18n-types';\nimport type { Translation } from './i18n-types';\nimport type { TranslationLoader } from './loaders';\nimport { jsonLoader } from './loaders';\nimport { browserLanguages, detectBrowserLanguage, safeGetItem, safeSetItem } from './i18n-utils';\nimport { parseCookie, serializeCookie } from './cookies';\nimport { formatIcu } from './icu';\nimport { ViewTransitionService } from './view-transition.service';\n\n/**\n * Headless language owner. State (signals, readonly): current language,\n * direction, loader status, dictionaries. Changes only via the methods below.\n * Side effects (persistence + `<html dir/lang>`) run in effects; everything\n * SSR-guarded. No components, no pipes, no styles inside.\n */\n@Service()\nexport class RiviniaI18n<L extends string = string> {\n private readonly _config = inject<RiviniaI18nConfig<L>>(RIVINIA_I18N_CONFIG);\n private readonly _viewTransition = inject(ViewTransitionService, { optional: true });\n private readonly _storageKey = this._config.storageKey ?? DEFAULT_STORAGE_KEY;\n private readonly _storageStrategy: StorageStrategy =\n this._config.storageStrategy ?? DEFAULT_STORAGE_STRATEGY;\n private readonly _autoApplyDirection: boolean =\n this._config.autoApplyDirection ?? DEFAULT_AUTO_APPLY_DIRECTION;\n /**\n * Injected (not global) document: the dir/lang effect renders on the\n * server too, avoiding an RTL first-paint shift on hydration.\n * Declared before any field initializer that reads storage.\n */\n private readonly _doc = inject(DOCUMENT);\n /** Present only on the server: used for cookie reads + transfer writes. */\n private readonly _request = inject(REQUEST, { optional: true });\n private readonly _transfer = inject(TransferState, { optional: true });\n\n private readonly _currentLanguageId = signal<L>(this._resolveInitialLanguage());\n private readonly _languages = signal<readonly Language<L>[]>(this._config.languages);\n private readonly _loadedTranslations = signal<Record<string, unknown>>({});\n /**\n * Explicit loader wins; otherwise the conventional JSON layout\n * (`assets/i18n/{language}.json` unless the consumer overrides the path).\n * The descriptor still code-splits: the fetch implementation loads only on\n * first resolve.\n */\n private readonly _getLoader: () => Promise<TranslationLoader<L>> =\n this._config.loader?.resolve ?? (() => jsonLoader().resolve() as Promise<TranslationLoader<L>>);\n private _resolvedLoader: TranslationLoader<L> | null = null;\n private readonly _translationsCache = new Map<L, Record<string, unknown>>();\n private readonly _inflight = new Map<L, Promise<{ data: Record<string, unknown>; ok: boolean }>>();\n /**\n * Out-of-order safety: a response reaches the visible signals only when it\n * belongs to the currently intended language (`_currentLanguageId()`).\n * Everything else stays cached. (A monotonic request token used to guard\n * this, but it over-constrained legitimate same-language loads.)\n */\n private _applyCount = 0;\n private _initialized = false;\n private readonly _tasks = inject(PendingTasks, { optional: true });\n\n readonly languageChanged = computed<L>(() => this._currentLanguageId());\n readonly languages = this._languages.asReadonly();\n readonly currentLanguage = this._currentLanguageId.asReadonly();\n\n readonly currentLanguageObject = computed<Language<L>>(() => {\n const id = this._currentLanguageId();\n return this._languages().find((l) => l.id === id) ?? this._languages()[0];\n });\n\n readonly dir = computed<Direction>(() => this.currentLanguageObject().dir);\n readonly isRtl = computed<boolean>(() => this.dir() === 'rtl');\n\n private readonly _loadingState = signal<'idle' | 'loading' | 'error'>('idle');\n private readonly _loadingError = signal<unknown>(null);\n\n /** Loader state for skeletons/spinners. */\n readonly loadingState = this._loadingState.asReadonly();\n readonly loadingError = this._loadingError.asReadonly();\n readonly isLoading = computed(() => this._loadingState() === 'loading');\n\n private readonly _ready = signal(false);\n /**\n * True once the initial language content is available (inline seed and/or\n * initial load settled) — or immediately when `preload: false` skips setup\n * loading. Gate first-paint skeletons on this, not on `isLoading`.\n */\n readonly ready = this._ready.asReadonly();\n\n constructor() {\n if (this._config.languages.length === 0) {\n throw new Error('[rivinia/i18n] At least one language must be provided in the languages array.');\n }\n if (!this._config.languages.some((l) => l.id === this._config.defaultLanguage)) {\n throw new Error(\n `[rivinia/i18n] defaultLanguage \"${this._config.defaultLanguage}\" must be one of the configured language IDs.`,\n );\n }\n\n effect(() => {\n const id = this._currentLanguageId();\n this._writeStored(id);\n });\n\n if (this._autoApplyDirection) {\n effect(() => {\n const lang = this.currentLanguageObject();\n const root = this._doc.documentElement;\n if (!root) return;\n root.dir = lang.dir;\n root.lang = lang.id;\n });\n }\n }\n\n getLanguage(id: L): Language<L> | undefined {\n return this._languages().find((l) => l.id === id);\n }\n\n /**\n * Runs the provider-setup loading: seeds inline dictionaries, then loads\n * the initial language (unless `preload: false`). Called automatically by\n * the `provideRiviniaI18n` app initializer; call manually only when driving\n * setup yourself. Idempotent. Never rejects (load failures land on\n * `loadingError`/`onLoadError`, inline seeds are preserved).\n */\n async initialize(): Promise<void> {\n if (this._initialized) return;\n this._initialized = true;\n const done = this._tasks?.add();\n try {\n const current = this._currentLanguageId();\n const transferred = this.readTransfer(current);\n if (transferred) {\n this._translationsCache.set(current, transferred);\n this._loadedTranslations.set(transferred);\n } else {\n const inline = this._config.translations?.[current];\n if (inline) {\n // Instant paint without touching the cache: the refresh below still\n // runs, so a successful loader response wins; on failure the seed\n // stays visible and the error surfaces on loadingState/onLoadError.\n this._loadedTranslations.set(inline);\n }\n if (this._config.preload ?? true) {\n await this._loadTranslations(current);\n }\n }\n } finally {\n this._ready.set(true);\n done?.();\n }\n }\n\n translate(key: string, defaultValue?: string, params?: TranslateParams): string;\n translate(key: string, params?: TranslateParams): string;\n translate(translations: Translation<L>): string;\n\n translate(\n keyOrTranslations: string | Translation<L>,\n defaultValueOrParams?: string | TranslateParams,\n maybeParams?: TranslateParams,\n ): string {\n if (typeof keyOrTranslations === 'string') {\n const { defaultValue, params } = normalizeKeyArgs(defaultValueOrParams, maybeParams);\n const loaded = this._loadedTranslations();\n const resolved = this._resolveKey(loaded, keyOrTranslations);\n if (resolved !== undefined) {\n return this.render(resolved, params);\n }\n const fallback = defaultValue ?? keyOrTranslations;\n return params ? this.render(fallback, params) : fallback;\n }\n const currentId = this._currentLanguageId();\n return keyOrTranslations[currentId] ?? Object.values(keyOrTranslations)[0] ?? '';\n }\n\n loadedTranslations = this._loadedTranslations.asReadonly();\n\n /** Preload without switching (use in `APP_INITIALIZER` / route guards). */\n async loadTranslations(\n languageId: L,\n opts?: { silent?: boolean },\n ): Promise<Record<string, unknown>> {\n return (await this._loadTranslations(languageId, opts)).data;\n }\n\n toggle(): void {\n const langs = this._languages();\n if (langs.length < 2) return;\n const currentId = this._currentLanguageId();\n const newId = currentId === langs[0].id ? langs[1].id : langs[0].id;\n this.applyLanguage(newId);\n }\n\n next(): void {\n const langs = this._languages();\n if (langs.length < 2) return;\n const currentIdx = langs.findIndex((l) => l.id === this._currentLanguageId());\n const nextIdx = (currentIdx + 1) % langs.length;\n this.applyLanguage(langs[nextIdx].id);\n }\n\n previous(): void {\n const langs = this._languages();\n if (langs.length < 2) return;\n const currentIdx = langs.findIndex((l) => l.id === this._currentLanguageId());\n const prevIdx = (currentIdx - 1 + langs.length) % langs.length;\n this.applyLanguage(langs[prevIdx].id);\n }\n\n setLanguage(id: L): void {\n if (this._config.switchStrategy === 'preload-first') {\n void this.setLanguageAsync(id);\n return;\n }\n this.applyLanguage(id);\n }\n\n /** Preload-first switch: await the dictionary, then flip — no raw-key flash.\n * A failed load aborts: language, direction and dictionary stay untouched. */\n async setLanguageAsync(id: L): Promise<void> {\n if (id === this._currentLanguageId()) return;\n if (!this._languages().some((l) => l.id === id)) return;\n const { ok } = await this._loadTranslations(id, { silent: true });\n if (!ok) return;\n this.applyLanguage(id);\n }\n\n /** Number formatting bound to the current language locale (cached Intl). */\n formatNumber(value: number, options?: Intl.NumberFormatOptions): string {\n return this.numberFormatter(options).format(value);\n }\n\n /** Date/time formatting bound to the current language locale (cached Intl). */\n formatDate(value: Date | number, options?: Intl.DateTimeFormatOptions): string {\n return this.dateTimeFormatter(options).format(value);\n }\n\n /** BCP-47 locale driving Intl + ICU plural rules (falls back to the id). */\n readonly locale = computed<string>(() => {\n return this.currentLanguageObject().locale ?? this._currentLanguageId();\n });\n\n private readonly _formatters = new Map<string, Intl.NumberFormat | Intl.DateTimeFormat>();\n\n private numberFormatter(options?: Intl.NumberFormatOptions): Intl.NumberFormat {\n const key = `n|${this.locale()}|${JSON.stringify(options ?? null)}`;\n let formatter = this._formatters.get(key) as Intl.NumberFormat | undefined;\n if (!formatter) {\n formatter = new Intl.NumberFormat(this.locale(), options);\n this._formatters.set(key, formatter);\n }\n return formatter;\n }\n\n private dateTimeFormatter(options?: Intl.DateTimeFormatOptions): Intl.DateTimeFormat {\n const key = `d|${this.locale()}|${JSON.stringify(options ?? null)}`;\n let formatter = this._formatters.get(key) as Intl.DateTimeFormat | undefined;\n if (!formatter) {\n formatter = new Intl.DateTimeFormat(this.locale(), options);\n this._formatters.set(key, formatter);\n }\n return formatter;\n }\n\n private applyLanguage(id: L, opts?: { skipLoad?: boolean }): void {\n if (id === this._currentLanguageId()) return;\n\n const lang = this._languages().find((l) => l.id === id);\n if (!lang) return;\n\n this._applyCount++;\n\n const apply = () => this._currentLanguageId.set(id);\n const vt = this._config.viewTransition;\n const useTransition =\n vt?.enabled &&\n (!vt.skipInitialTransition || this._applyCount > 1) &&\n this._viewTransition != null;\n\n if (useTransition) {\n vt!.onViewTransitionCreated?.({ language: id, direction: lang.dir });\n this._viewTransition!.run(apply);\n } else {\n apply();\n }\n\n if (!opts?.skipLoad) {\n void this._loadTranslations(id);\n }\n }\n\n private render(template: string, params?: TranslateParams): string {\n if (!params) return template;\n if (!template.includes('{')) return template;\n try {\n return formatIcu(template, params, this.locale());\n } catch {\n return template;\n }\n }\n\n private async _loadTranslations(\n languageId: L,\n opts?: { silent?: boolean },\n ): Promise<{ data: Record<string, unknown>; ok: boolean }> {\n // A dictionary only ever reaches the visible signals when it belongs to\n // the currently intended language. Anything else (slow out-of-order\n // responses, explicit preloads of other languages) stays cached.\n const current = (): boolean => languageId === this._currentLanguageId();\n const cached = this._translationsCache.get(languageId);\n if (cached) {\n if (!opts?.silent && current()) {\n this._loadedTranslations.set(cached);\n }\n return { data: cached, ok: true };\n }\n\n const inflight = this._inflight.get(languageId);\n if (inflight) return inflight;\n\n this._loadingState.set('loading');\n\n const task: Promise<{ data: Record<string, unknown>; ok: boolean }> = (async () => {\n try {\n if (!this._resolvedLoader) {\n this._resolvedLoader = await this._getLoader!();\n }\n const translations = await this._resolvedLoader.load(languageId);\n\n this._translationsCache.set(languageId, translations);\n this.writeTransfer(languageId, translations);\n\n if (!opts?.silent && current()) {\n this._loadedTranslations.set(translations);\n this._loadingError.set(null);\n this._loadingState.set('idle');\n }\n\n return { data: translations, ok: true };\n } catch (error) {\n if (current()) {\n this._loadingError.set(error);\n this._loadingState.set('error');\n }\n this._config.onLoadError?.(languageId, error);\n return { data: {}, ok: false };\n } finally {\n this._inflight.delete(languageId);\n if (this._inflight.size === 0 && this._loadingState() === 'loading') {\n this._loadingState.set('idle');\n }\n }\n })();\n\n this._inflight.set(languageId, task);\n return task;\n }\n\n /**\n * Reads the persisted language. Cookie strategy: server reads the request\n * `Cookie` header (no hydration mismatch), browser reads `document.cookie`.\n * Everything else delegates to the SSR-safe storage helpers.\n */\n private _readStored(): string | null {\n if (this._storageStrategy === 'cookie') {\n const header = this._request?.headers.get('cookie') ?? null;\n if (header !== null) return parseCookie(header, this._storageKey);\n try {\n return parseCookie(this._doc.cookie, this._storageKey);\n } catch {\n return null;\n }\n }\n return safeGetItem(this._storageKey, this._storageStrategy);\n }\n\n /** Persists the language. Server never writes (response cookies are app-owned). */\n private _writeStored(id: L): void {\n if (this._storageStrategy === 'cookie') {\n if (this._request) return;\n try {\n this._doc.cookie = serializeCookie(this._storageKey, id);\n } catch {\n // Best-effort persistence.\n }\n return;\n }\n safeSetItem(this._storageKey, id, this._storageStrategy);\n }\n\n private transferKey(languageId: L): StateKey<Record<string, unknown>> {\n return makeStateKey<Record<string, unknown>>(`rivinia.i18n.dict.${languageId}`);\n }\n\n /** Consumes server-rendered dictionaries so the client never refetches. */\n private readTransfer(languageId: L): Record<string, unknown> | null {\n const transfer = this._transfer;\n if (!transfer) return null;\n const key = this.transferKey(languageId);\n if (!transfer.hasKey(key)) return null;\n const dict = transfer.get(key, null);\n transfer.remove(key);\n return dict;\n }\n\n /** Stores freshly loaded dictionaries for hydration (server only). */\n private writeTransfer(languageId: L, dict: Record<string, unknown>): void {\n if (!this._request) return;\n this._transfer?.set(this.transferKey(languageId), dict);\n }\n\n private _resolveKey(obj: Record<string, unknown>, path: string): string | undefined {\n const value = path.split('.').reduce<unknown>(\n (acc, segment) =>\n acc && typeof acc === 'object'\n ? (acc as Record<string, unknown>)[segment]\n : undefined,\n obj,\n );\n if (typeof value === 'string') return value;\n if (typeof value === 'number' || typeof value === 'boolean') return String(value);\n return undefined;\n }\n\n private _resolveInitialLanguage(): L {\n const stored = this._readStored();\n if (stored && this._config.languages.some((l) => l.id === stored)) {\n return stored as L;\n }\n if (this._config.detectBrowser) {\n const detected = detectBrowserLanguage(\n this._config.languages.map((l) => l.id),\n browserLanguages(),\n );\n if (detected) return detected;\n }\n return this._config.defaultLanguage;\n }\n}\n\nfunction normalizeKeyArgs(\n second?: string | TranslateParams,\n third?: TranslateParams,\n): { defaultValue?: string; params?: TranslateParams } {\n if (second && typeof second === 'object') {\n return { params: second };\n }\n return { defaultValue: second, params: third };\n}\n","import {\n EnvironmentProviders,\n inject,\n makeEnvironmentProviders,\n provideAppInitializer,\n} from '@angular/core';\nimport { RIVINIA_I18N_CONFIG, type RiviniaI18nConfig } from './i18n-config';\nimport { RiviniaI18n } from './rivinia-i18n';\n\n/**\n * Configures `@rivinia/i18n` for the application. Call once at bootstrap.\n * Also registers an app initializer that loads the initial language before\n * first paint (opt out with `preload: false`).\n *\n * @example\n * ```ts\n * provideRiviniaI18n({\n * defaultLanguage: 'ar',\n * languages: [\n * { id: 'ar', nativeName: 'العربية', dir: 'rtl' },\n * { id: 'en', nativeName: 'English', dir: 'ltr' },\n * ],\n * })\n * ```\n */\nexport function provideRiviniaI18n<L extends string>(\n config: RiviniaI18nConfig<L>,\n): EnvironmentProviders {\n return makeEnvironmentProviders([\n { provide: RIVINIA_I18N_CONFIG, useValue: config },\n provideAppInitializer(() => {\n const i18n = inject(RiviniaI18n) as RiviniaI18n<string>;\n return i18n.initialize();\n }),\n ]);\n}\n\n/** Shorthand for `inject(RiviniaI18n)` — preserves the configured language union. */\nexport function injectRiviniaI18n<L extends string = string>(): RiviniaI18n<L> {\n return inject(RiviniaI18n) as unknown as RiviniaI18n<L>;\n}\n\n/**\n * Binds a config and its typed accessors together so `L` is inferred once\n * from the configuration instead of being lost at the injection site.\n *\n * @example\n * ```ts\n * export const i18n = defineRiviniaI18n({\n * defaultLanguage: 'ar',\n * languages: [\n * { id: 'ar', nativeName: 'العربية', dir: 'rtl' },\n * { id: 'en', nativeName: 'English', dir: 'ltr' },\n * ],\n * });\n * // app.config.ts\n * providers: [i18n.provide()]\n * // anywhere (typed 'ar' | 'en'):\n * const lang = i18n.inject();\n * ```\n */\nexport function defineRiviniaI18n<L extends string>(config: RiviniaI18nConfig<L>): {\n readonly config: RiviniaI18nConfig<L>;\n provide: () => EnvironmentProviders;\n inject: () => RiviniaI18n<L>;\n} {\n return {\n config,\n provide: () => provideRiviniaI18n(config),\n inject: () => injectRiviniaI18n<L>(),\n };\n}\n","import { Pipe, inject } from '@angular/core';\nimport { RiviniaI18n } from './rivinia-i18n';\nimport type { TranslateParams } from './i18n-types';\nimport type { Translation } from './i18n-types';\n\n/**\n * Template pipe delegating to `RiviniaI18n.translate()`.\n *\n * Impure (`pure: false`) by necessity: the service reads signals on every\n * call, and a pure pipe would not re-evaluate on language switches. For long\n * lists prefer `translate()` in component code over this pipe.\n */\n@Pipe({\n name: 'rTranslate',\n standalone: true,\n pure: false,\n})\nexport class RTranslatePipe<L extends string = string> {\n private readonly _i18n = inject(RiviniaI18n<L>);\n\n transform(key: string, defaultValue?: string, params?: TranslateParams): string;\n transform(key: string, params?: TranslateParams): string;\n transform(translations: Translation<L>): string;\n\n transform(\n keyOrTranslations: string | Translation<L>,\n defaultValueOrParams?: string | TranslateParams,\n maybeParams?: TranslateParams,\n ): string {\n return this._i18n.translate(\n keyOrTranslations as string,\n defaultValueOrParams as string,\n maybeParams as TranslateParams,\n );\n }\n}\n"],"mappings":";;AAiBA,SAAgB,WAAW,SAA2B;CACpD,OAAO,EACL,MAAM,UAAO;EACX,MAAM,EAAE,eAAe,MAAM,OAAO;EACpC,OAAO,IAAI,WAAW,OAAO;CAC/B,EACD;AACH;AAQA,SAAgB,WAAW,SAA0B;CACnD,OAAO,EACL,MAAM,UAAO;EACX,MAAM,EAAE,eAAe,MAAM,OAAO;EACpC,OAAO,IAAI,WAAW,OAAO;CAC/B,EACD;AACH;AAOA,SAAgB,aAAa,SAA4B;CACvD,OAAO,EACL,MAAM,UAAO;EACX,MAAM,EAAE,iBAAiB,MAAM,OAAO;EACtC,OAAO,IAAI,aAAa,OAAO;CACjC,EACD;AACH;AAGA,SAAgB,aACd,MAAuD;CAEvD,OAAO,EACL,MAAM,UAAO;EACX,OAAO,EAAE,KAAI;CACf,EACD;AACH;AC9DA,SAAS,WAAW,UAAyB;CAI3C,IAAI,aAAa,UAAU,aAAa,UAAU,OAAO;CACzD,IAAI,OAAO,WAAW,aAAa,OAAO;CAC1C,IAAI;EACF,OAAO,aAAa,YAAY,OAAO,iBAAiB,OAAO;CACjE,QAAQ;EACN,OAAO;CACT;AACF;AAGA,SAAgB,YAAY,KAAa,UAAyB;CAChE,MAAM,UAAU,WAAW,QAAQ;CACnC,IAAI,CAAC,SAAS,OAAO;CACrB,IAAI;EACF,OAAO,QAAQ,QAAQ,GAAG;CAC5B,QAAQ;EACN,OAAO;CACT;AACF;AAGA,SAAgB,YAAY,KAAa,OAAe,UAAyB;CAC/E,MAAM,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B;CAC/B,OAAO,OAAO,WAAW;AAC3B;AAqBA,SAAgB,kBAAoC,QAA4B;CAK9E,OAAO;EACL;EACA,eAAe,mBAAmB,MAAM;EACxC,cAAc,kBAAiB;CAChC;AACH;ACtDA,IAAa,iBAAb,MAAa,eAAc;CACR,QAAQ,OAAO,WAAc;CAM9C,UACE,mBACA,sBACA,aAA6B;EAE7B,OAAO,KAAK,MAAM,UAChB,mBACA,sBACA,WAA8B;CAElC;CAjBW,OAAA,OAAA,GAAA,mBAAA;EAAA,YAAA;EAAA,SAAA;EAAA,UAAA;EAAA,MAAA;EAAc,MAAA,CAAA;EAAA,QAAA,GAAA,gBAAA;CAAA,CAAA;CAAd,OAAA,QAAA,GAAA,gBAAA;EAAA,YAAA;EAAA,SAAA;EAAA,UAAA;EAAA,MAAA;EAAc,cAAA;EAAA,MAAA;EAAA,MAAA;CAAA,CAAA;;AAAd,GAAA,yBAAA;CAAA,YAAA;CAAA,SAAA;CAAA,UAAA;CAAA,MAAA;CAAc,YAAA,CAAA;EAL1B,MAAA;EAAK,MAAA,CAAA;GACJ,MAAM;GACN,YAAY;GACZ,MAAM;EACP,CAAA"}
1
+ {"version":3,"file":"rivinia-i18n.mjs","names":[],"sources":["../../../projects/i18n/src/lib/loaders.ts","../../../projects/i18n/src/lib/i18n-utils.ts","../../../projects/i18n/src/lib/cookies.ts","../../../projects/i18n/src/lib/icu.ts","../../../projects/i18n/src/lib/i18n-config.ts","../../../projects/i18n/src/lib/view-transition.service.ts","../../../projects/i18n/src/lib/rivinia-i18n.ts","../../../projects/i18n/src/lib/provide-i18n.ts","../../../projects/i18n/src/lib/translate.pipe.ts"],"sourcesContent":["/**\n * Pluggable key-dictionary loader. Returns a flat/nested JSON-compatible map\n * merged into `loadedTranslations` and read by key-based `translate(key)`.\n */\nexport interface TranslationLoader<L extends string = string> {\n load(language: L): Promise<Record<string, unknown>>;\n}\n\n/**\n * Lazy descriptor: `resolve()` dynamic-imports the real implementation, so\n * loader code splits out of the main bundle until first use. Resolved once\n * and cached by the service.\n */\nexport interface LoaderDescriptor<L extends string = string> {\n resolve(): Promise<TranslationLoader<L>>;\n}\n\nexport function jsonLoader(options?: { path?: string }): LoaderDescriptor<string> {\n return {\n async resolve() {\n const { JsonLoader } = await import('./json-loader.impl');\n return new JsonLoader(options);\n },\n };\n}\n\nexport interface HttpLoaderOptions {\n readonly endpoint: string;\n readonly method?: string;\n readonly buildUrl?: (language: string) => string;\n}\n\nexport function httpLoader(options: HttpLoaderOptions): LoaderDescriptor<string> {\n return {\n async resolve() {\n const { HttpLoader } = await import('./http-loader.impl');\n return new HttpLoader(options);\n },\n };\n}\n\nexport interface RemoteLoaderOptions {\n readonly url: (language: string) => string;\n readonly headers?: Record<string, string>;\n}\n\nexport function remoteLoader(options: RemoteLoaderOptions): LoaderDescriptor<string> {\n return {\n async resolve() {\n const { RemoteLoader } = await import('./remote-loader.impl');\n return new RemoteLoader(options);\n },\n };\n}\n\n/** Wraps any function as a loader (mocks, in-memory, third-party SDKs). */\nexport function customLoader<L extends string = string>(\n load: (language: L) => Promise<Record<string, unknown>>,\n): LoaderDescriptor<L> {\n return {\n async resolve() {\n return { load };\n },\n };\n}\n","import type { StorageStrategy } from './i18n-types';\n\nfunction getStorage(strategy: StorageStrategy): Storage | null {\n // NOTE: 'cookie' resolves to null on purpose — cookies need request/document\n // context, so the service handles that strategy itself (server REQUEST\n // header, browser document.cookie). See RiviniaI18n storage methods.\n if (strategy === 'none' || strategy === 'cookie') return null;\n if (typeof window === 'undefined') return null;\n try {\n return strategy === 'session' ? window.sessionStorage : window.localStorage;\n } catch {\n return null;\n }\n}\n\n/** SSR-safe read. Returns `null` off-browser, on denial, or when missing. */\nexport function safeGetItem(key: string, strategy: StorageStrategy): string | null {\n const storage = getStorage(strategy);\n if (!storage) return null;\n try {\n return storage.getItem(key);\n } catch {\n return null;\n }\n}\n\n/** SSR-safe write. Silently no-ops off-browser or on denial. */\nexport function safeSetItem(key: string, value: string, strategy: StorageStrategy): void {\n const storage = getStorage(strategy);\n if (!storage) return;\n try {\n storage.setItem(key, value);\n } catch {\n // Intentionally silent: persistence is best-effort.\n }\n}\n\n/**\n * Matches the browser language priority list against supported ids, in order.\n * For each browser entry (highest preference first) tries the exact tag, then\n * its base subtag (`ar-EG` → `ar`). Returns the first hit, or `null`.\n * Pure and exported for testing — pass `navigator.languages` in app code.\n */\nexport function detectBrowserLanguage<T extends string>(\n supportedIds: readonly T[],\n browserLanguages: readonly string[] | undefined,\n): T | null {\n if (!browserLanguages || browserLanguages.length === 0) return null;\n const supported = supportedIds.map((id) => id.toLowerCase());\n for (const raw of browserLanguages) {\n const tag = raw.trim().toLowerCase();\n if (!tag) continue;\n const exact = supported.indexOf(tag);\n if (exact !== -1) return supportedIds[exact];\n const base = tag.split(/[-_]/)[0];\n if (base && base !== tag) {\n const hit = supported.indexOf(base);\n if (hit !== -1) return supportedIds[hit];\n }\n }\n return null;\n}\n\n/** Browser language list, `undefined` off-browser (SSR-safe input for detection). */\nexport function browserLanguages(): readonly string[] | undefined {\n if (typeof window === 'undefined' || typeof navigator === 'undefined') return undefined;\n try {\n if (Array.isArray(navigator.languages) && navigator.languages.length > 0) {\n return [...navigator.languages];\n }\n return typeof navigator.language === 'string' ? [navigator.language] : undefined;\n } catch {\n return undefined;\n }\n}\n","/**\n * Cookie helpers for the `'cookie'` storage strategy. Pure and SSR-testable:\n * the service supplies the header (server `REQUEST`) or `document.cookie`\n * (browser); these functions only parse and serialize.\n */\n\n/** Extracts a cookie value by name from a `Cookie` header or `document.cookie`. */\nexport function parseCookie(header: string | null | undefined, name: string): string | null {\n if (!header) return null;\n const prefix = `${name}=`;\n for (const part of header.split(';')) {\n const trimmed = part.trim();\n if (trimmed.startsWith(prefix)) {\n try {\n return decodeURIComponent(trimmed.slice(prefix.length));\n } catch {\n return trimmed.slice(prefix.length);\n }\n }\n }\n return null;\n}\n\n/** Serializes a language cookie (Lax, root path, one year). */\nexport function serializeCookie(\n name: string,\n value: string,\n options?: { secure?: boolean },\n): string {\n const base = `${name}=${encodeURIComponent(value)}; Path=/; Max-Age=31536000; SameSite=Lax`;\n return options?.secure ? `${base}; Secure` : base;\n}\n\n/**\n * Decides whether the language cookie gets `Secure`: only on `https:`, never\n * on `localhost` (dev TLS included — `Secure` there buys nothing and risks\n * silent persistence loss). Pure and SSR-safe: unknown locations → `false`.\n * The server never writes cookies regardless (app-owned responses).\n */\nexport function shouldSecureCookie(\n location: { protocol?: string; hostname?: string } | null | undefined,\n): boolean {\n try {\n if (!location) return false;\n if (location.protocol !== 'https:') return false;\n if (location.hostname === 'localhost') return false;\n return true;\n } catch {\n return false;\n }\n}\n","import type { TranslateParams } from './i18n-types';\n\n/**\n * Minimal ICU MessageFormat subset: `{name}` interpolation, `{n, plural, …}`,\n * `{x, select, …}`, `#` inside plurals, and nesting. Categories resolve via\n * the native `Intl.PluralRules(locale)` — Arabic gets all six forms\n * (zero/one/two/few/many/other) with zero extra dependencies.\n *\n * Supported (and ONLY these — documented subset, translators beware):\n * - `{count, plural, =0 {none} one {# item} other {# items}}`\n * - `{gender, select, male {He} female {She} other {They}}`\n * - `{name}` plain interpolation (missing params keep the placeholder)\n *\n * Malformed input never throws: the raw segment is returned as-is.\n */\nexport function formatIcu(\n template: string,\n params: TranslateParams,\n locale: string,\n): string {\n return parseMessage(template, 0, template.length, params, locale, null).text;\n}\n\ninterface Parsed {\n text: string;\n /** Index of the closing `}` (or `end` when the level ran out). */\n next: number;\n ok: boolean;\n}\n\nfunction parseMessage(\n src: string,\n start: number,\n end: number,\n params: TranslateParams,\n locale: string,\n pluralValue: number | null,\n): Parsed {\n let out = '';\n let i = start;\n while (i < end) {\n const ch = src[i];\n if (ch === '{') {\n const arg = parseArgument(src, i, end, params, locale, pluralValue);\n if (!arg.ok) return { text: out + src.slice(i, end), next: end, ok: true };\n out += arg.text;\n i = arg.next;\n } else if (ch === '}') {\n return { text: out, next: i, ok: true };\n } else if (ch === '#' && pluralValue !== null) {\n out += String(pluralValue);\n i++;\n } else {\n out += ch;\n i++;\n }\n }\n return { text: out, next: i, ok: true };\n}\n\nfunction parseArgument(\n src: string,\n start: number,\n end: number,\n params: TranslateParams,\n locale: string,\n outerPlural: number | null,\n): Parsed {\n let i = skipSpaces(src, start + 1, end);\n const name = readWord(src, i, end);\n i = skipSpaces(src, name.next, end);\n if (i >= end) return { text: src.slice(start, end), next: end, ok: true };\n if (src[i] === '}') {\n const value = params[name.word];\n const rendered =\n value === undefined || value === null || name.word === ''\n ? src.slice(start, i + 1)\n : String(value);\n return { text: rendered, next: i + 1, ok: true };\n }\n if (src[i] !== ',' || name.word === '') {\n return { text: src.slice(start, end), next: end, ok: true };\n }\n i = skipSpaces(src, i + 1, end);\n const type = readWord(src, i, end);\n i = skipSpaces(src, type.next, end);\n if (i >= end || src[i] !== ',') return { text: src.slice(start, end), next: end, ok: true };\n if (type.word !== 'plural' && type.word !== 'select') {\n return { text: src.slice(start, end), next: end, ok: true };\n }\n i++;\n const numeric =\n type.word === 'plural' ? toFiniteNumber(params[name.word]) : null;\n const branches = new Map<string, string>();\n i = skipSpaces(src, i, end);\n let closed = false;\n while (i < end) {\n i = skipSpaces(src, i, end);\n if (i < end && src[i] === '}') {\n closed = true;\n break;\n }\n const sel = readSelector(src, i, end);\n if (sel.selector === null) return { text: src.slice(start, end), next: end, ok: true };\n i = skipSpaces(src, sel.next, end);\n if (i >= end || src[i] !== '{') {\n return { text: src.slice(start, end), next: end, ok: true };\n }\n // Bodies render immediately: '#' binds to THIS plural's number, or to an\n // outer plural when nested (select inherits, nested plural overrides).\n const body = parseMessage(\n src,\n i + 1,\n end,\n params,\n locale,\n numeric ?? outerPlural,\n );\n branches.set(sel.selector, body.text);\n i = body.next + 1;\n }\n if (!closed) return { text: src.slice(start, end), next: end, ok: true };\n if (type.word === 'select') {\n const raw = params[name.word];\n const key = raw === undefined || raw === null ? '' : String(raw);\n return { text: branches.get(key) ?? branches.get('other') ?? '', next: i + 1, ok: true };\n }\n if (numeric === null) return { text: branches.get('other') ?? '', next: i + 1, ok: true };\n const exact = branches.get(`=${numeric}`);\n if (exact !== undefined) return { text: exact, next: i + 1, ok: true };\n let category: string;\n try {\n category = new Intl.PluralRules(locale).select(numeric);\n } catch {\n category = 'other';\n }\n return { text: branches.get(category) ?? branches.get('other') ?? '', next: i + 1, ok: true };\n}\n\nfunction toFiniteNumber(value: string | number | boolean | undefined): number | null {\n if (typeof value === 'number') return Number.isFinite(value) ? value : null;\n if (typeof value === 'string' && value.trim() !== '') {\n const n = Number(value);\n return Number.isFinite(n) ? n : null;\n }\n return null;\n}\n\nfunction skipSpaces(src: string, i: number, end: number): number {\n while (i < end && /\\s/.test(src[i])) i++;\n return i;\n}\n\nfunction readWord(src: string, i: number, end: number): { word: string; next: number } {\n const start = skipSpaces(src, i, end);\n let j = start;\n while (j < end && /[^\\s,}]+/.test(src[j])) j++;\n return { word: src.slice(start, j), next: j };\n}\n\nfunction readSelector(\n src: string,\n i: number,\n end: number,\n): { selector: string | null; next: number } {\n i = skipSpaces(src, i, end);\n if (i < end && src[i] === '=') {\n let j = i + 1;\n if (j < end && src[j] === '-') j++;\n const digits = j;\n while (j < end && /[0-9]/.test(src[j])) j++;\n if (j < end && src[j] === '.' && j + 1 < end && /[0-9]/.test(src[j + 1])) {\n j++;\n while (j < end && /[0-9]/.test(src[j])) j++;\n }\n if (j === digits) return { selector: null, next: i };\n return { selector: src.slice(i, j), next: j };\n }\n const word = readWord(src, i, end);\n if (!word.word) return { selector: null, next: i };\n return { selector: word.word, next: word.next };\n}\n","import { InjectionToken } from '@angular/core';\nimport type { Language, StorageStrategy, SwitchStrategy, ViewTransitionConfig } from './i18n-types';\nimport type { LoaderDescriptor } from './loaders';\n\n/**\n * Global configuration for `@rivinia/i18n`.\n */\nexport interface RiviniaI18nConfig<T extends string = string> {\n readonly languages: readonly Language<T>[];\n readonly defaultLanguage: T;\n readonly storageKey?: string;\n readonly storageStrategy?: StorageStrategy;\n readonly autoApplyDirection?: boolean;\n readonly viewTransition?: ViewTransitionConfig;\n /**\n * Dictionary source. Defaults to `jsonLoader()` — the conventional\n * `i18n/{language}.json` layout (files in `public/i18n/`, served from the\n * site root). Override with any descriptor\n * (custom path, HTTP endpoint, in-memory). Inline-only apps that want zero\n * network traffic pass `customLoader(async () => ({}))`.\n */\n readonly loader?: LoaderDescriptor<T>;\n readonly switchStrategy?: SwitchStrategy;\n /** Called when a dictionary load fails. The service still falls back safely. */\n readonly onLoadError?: (language: T, error: unknown) => void;\n /**\n * Load the initial language during provider setup (before first paint).\n * SSR waits via `PendingTasks`. Set `false` to skip (e.g. fully inline apps\n * that call `loadTranslations` themselves).\n * @default true\n */\n readonly preload?: boolean;\n /**\n * Inline per-language dictionaries. Seeded before any network load (zero\n * network + SSR-safe first paint); a successful loader response still wins.\n */\n readonly translations?: Partial<Record<T, Record<string, unknown>>>;\n /**\n * Match `navigator.languages` against supported ids on first visit\n * (stored preference always wins; base tags match, e.g. `ar-EG` → `ar`).\n * @default false — explicit opt-in, no surprises.\n */\n readonly detectBrowser?: boolean;\n}\n\n/**\n * Internal configuration token. Consumers must use `provideRiviniaI18n()`.\n * @internal\n */\nexport const RIVINIA_I18N_CONFIG = new InjectionToken<RiviniaI18nConfig>('RIVINIA_I18N_CONFIG');\n\nexport const DEFAULT_STORAGE_KEY = 'rivinia.i18n.language';\nexport const DEFAULT_STORAGE_STRATEGY: StorageStrategy = 'local';\nexport const DEFAULT_AUTO_APPLY_DIRECTION = true;\n","import { DOCUMENT, Service, inject } from '@angular/core';\n\n/** Progressive-enhancement wrapper around the View Transition API. */\n@Service()\nexport class ViewTransitionService {\n private readonly _doc = inject(DOCUMENT);\n\n run(callback: () => void): void {\n const doc = this._doc as Document & {\n startViewTransition?: (callback: () => void) => unknown;\n };\n if (typeof doc.startViewTransition === 'function') {\n doc.startViewTransition(callback);\n } else {\n callback();\n }\n }\n}\n","import {\n DOCUMENT,\n PendingTasks,\n REQUEST,\n Service,\n TransferState,\n computed,\n effect,\n inject,\n makeStateKey,\n signal,\n type StateKey,\n} from '@angular/core';\nimport {\n DEFAULT_AUTO_APPLY_DIRECTION,\n DEFAULT_STORAGE_KEY,\n DEFAULT_STORAGE_STRATEGY,\n RIVINIA_I18N_CONFIG,\n type RiviniaI18nConfig,\n} from './i18n-config';\nimport type { Direction } from './i18n-types';\nimport type { Language } from './i18n-types';\nimport type { StorageStrategy } from './i18n-types';\nimport type { TranslateParams } from './i18n-types';\nimport type { Translation } from './i18n-types';\nimport type { TranslationLoader } from './loaders';\nimport { jsonLoader } from './loaders';\nimport { browserLanguages, detectBrowserLanguage, safeGetItem, safeSetItem } from './i18n-utils';\nimport { parseCookie, serializeCookie, shouldSecureCookie } from './cookies';\nimport { formatIcu } from './icu';\nimport { ViewTransitionService } from './view-transition.service';\n\n/**\n * Headless language owner. State (signals, readonly): current language,\n * direction, loader status, dictionaries. Changes only via the methods below.\n * Side effects (persistence + `<html dir/lang>`) run in effects; everything\n * SSR-guarded. No components, no pipes, no styles inside.\n */\n@Service()\nexport class RiviniaI18n<L extends string = string> {\n private readonly _config = inject<RiviniaI18nConfig<L>>(RIVINIA_I18N_CONFIG);\n private readonly _viewTransition = inject(ViewTransitionService, { optional: true });\n private readonly _storageKey = this._config.storageKey ?? DEFAULT_STORAGE_KEY;\n private readonly _storageStrategy: StorageStrategy =\n this._config.storageStrategy ?? DEFAULT_STORAGE_STRATEGY;\n private readonly _autoApplyDirection: boolean =\n this._config.autoApplyDirection ?? DEFAULT_AUTO_APPLY_DIRECTION;\n /**\n * Injected (not global) document: the dir/lang effect renders on the\n * server too, avoiding an RTL first-paint shift on hydration.\n * Declared before any field initializer that reads storage.\n */\n private readonly _doc = inject(DOCUMENT);\n /** Present only on the server: used for cookie reads + transfer writes. */\n private readonly _request = inject(REQUEST, { optional: true });\n private readonly _transfer = inject(TransferState, { optional: true });\n\n private readonly _currentLanguageId = signal<L>(this._resolveInitialLanguage());\n private readonly _languages = signal<readonly Language<L>[]>(this._config.languages);\n private readonly _loadedTranslations = signal<Record<string, unknown>>({});\n /**\n * Explicit loader wins; otherwise the conventional JSON layout\n * (`i18n/{language}.json` — files in `public/i18n/`, served from the site\n * root — unless the consumer overrides the path).\n * The descriptor still code-splits: the fetch implementation loads only on\n * first resolve.\n */\n private readonly _getLoader: () => Promise<TranslationLoader<L>> =\n this._config.loader?.resolve ?? (() => jsonLoader().resolve() as Promise<TranslationLoader<L>>);\n private _resolvedLoader: TranslationLoader<L> | null = null;\n private readonly _translationsCache = new Map<L, Record<string, unknown>>();\n private readonly _inflight = new Map<\n L,\n Promise<{ data: Record<string, unknown>; ok: boolean }>\n >();\n /**\n * Out-of-order safety: a response reaches the visible signals only when it\n * belongs to the currently intended language (`_currentLanguageId()`).\n * Everything else stays cached. (A monotonic request token used to guard\n * this, but it over-constrained legitimate same-language loads.)\n */\n private _applyCount = 0;\n private _initialized = false;\n private readonly _tasks = inject(PendingTasks, { optional: true });\n\n readonly languageChanged = computed<L>(() => this._currentLanguageId());\n readonly languages = this._languages.asReadonly();\n readonly currentLanguage = this._currentLanguageId.asReadonly();\n\n readonly currentLanguageObject = computed<Language<L>>(() => {\n const id = this._currentLanguageId();\n return this._languages().find((l) => l.id === id) ?? this._languages()[0];\n });\n\n readonly dir = computed<Direction>(() => this.currentLanguageObject().dir);\n readonly isRtl = computed<boolean>(() => this.dir() === 'rtl');\n\n private readonly _loadingState = signal<'idle' | 'loading' | 'error'>('idle');\n private readonly _loadingError = signal<unknown>(null);\n\n /** Loader state for skeletons/spinners. */\n readonly loadingState = this._loadingState.asReadonly();\n readonly loadingError = this._loadingError.asReadonly();\n readonly isLoading = computed(() => this._loadingState() === 'loading');\n\n private readonly _ready = signal(false);\n /**\n * True once the initial language content is available (inline seed and/or\n * initial load settled) — or immediately when `preload: false` skips setup\n * loading. Gate first-paint skeletons on this, not on `isLoading`.\n */\n readonly ready = this._ready.asReadonly();\n\n constructor() {\n if (this._config.languages.length === 0) {\n throw new Error(\n '[rivinia/i18n] At least one language must be provided in the languages array.',\n );\n }\n if (!this._config.languages.some((l) => l.id === this._config.defaultLanguage)) {\n throw new Error(\n `[rivinia/i18n] defaultLanguage \"${this._config.defaultLanguage}\" must be one of the configured language IDs.`,\n );\n }\n\n effect(() => {\n const id = this._currentLanguageId();\n this._writeStored(id);\n });\n\n if (this._autoApplyDirection) {\n effect(() => {\n const lang = this.currentLanguageObject();\n const root = this._doc.documentElement;\n if (!root) return;\n root.dir = lang.dir;\n root.lang = lang.id;\n });\n }\n }\n\n getLanguage(id: L): Language<L> | undefined {\n return this._languages().find((l) => l.id === id);\n }\n\n /**\n * Runs the provider-setup loading: seeds inline dictionaries, then loads\n * the initial language (unless `preload: false`). Called automatically by\n * the `provideRiviniaI18n` app initializer; call manually only when driving\n * setup yourself. Idempotent. Never rejects (load failures land on\n * `loadingError`/`onLoadError`, inline seeds are preserved).\n */\n async initialize(): Promise<void> {\n if (this._initialized) return;\n this._initialized = true;\n const done = this._tasks?.add();\n try {\n const current = this._currentLanguageId();\n const transferred = this.readTransfer(current);\n if (transferred) {\n this._translationsCache.set(current, transferred);\n this._loadedTranslations.set(transferred);\n } else {\n const inline = this._config.translations?.[current];\n if (inline) {\n // Instant paint without touching the cache: the refresh below still\n // runs, so a successful loader response wins; on failure the seed\n // stays visible and the error surfaces on loadingState/onLoadError.\n this._loadedTranslations.set(inline);\n }\n if (this._config.preload ?? true) {\n await this._loadTranslations(current);\n }\n }\n } finally {\n this._ready.set(true);\n done?.();\n }\n }\n\n translate(key: string, defaultValue?: string, params?: TranslateParams): string;\n translate(key: string, params?: TranslateParams): string;\n translate(translations: Translation<L>): string;\n\n translate(\n keyOrTranslations: string | Translation<L>,\n defaultValueOrParams?: string | TranslateParams,\n maybeParams?: TranslateParams,\n ): string {\n if (typeof keyOrTranslations === 'string') {\n const { defaultValue, params } = normalizeKeyArgs(defaultValueOrParams, maybeParams);\n const loaded = this._loadedTranslations();\n const resolved = this._resolveKey(loaded, keyOrTranslations);\n if (resolved !== undefined) {\n return this.render(resolved, params);\n }\n const fallback = defaultValue ?? keyOrTranslations;\n return params ? this.render(fallback, params) : fallback;\n }\n const currentId = this._currentLanguageId();\n return keyOrTranslations[currentId] ?? Object.values(keyOrTranslations)[0] ?? '';\n }\n\n loadedTranslations = this._loadedTranslations.asReadonly();\n\n /** Preload without switching (use in `APP_INITIALIZER` / route guards). */\n async loadTranslations(\n languageId: L,\n opts?: { silent?: boolean },\n ): Promise<Record<string, unknown>> {\n return (await this._loadTranslations(languageId, opts)).data;\n }\n\n toggle(): void {\n const langs = this._languages();\n if (langs.length < 2) return;\n const currentId = this._currentLanguageId();\n const newId = currentId === langs[0].id ? langs[1].id : langs[0].id;\n this.applyLanguage(newId);\n }\n\n next(): void {\n const langs = this._languages();\n if (langs.length < 2) return;\n const currentIdx = langs.findIndex((l) => l.id === this._currentLanguageId());\n const nextIdx = (currentIdx + 1) % langs.length;\n this.applyLanguage(langs[nextIdx].id);\n }\n\n previous(): void {\n const langs = this._languages();\n if (langs.length < 2) return;\n const currentIdx = langs.findIndex((l) => l.id === this._currentLanguageId());\n const prevIdx = (currentIdx - 1 + langs.length) % langs.length;\n this.applyLanguage(langs[prevIdx].id);\n }\n\n setLanguage(id: L): void {\n if (this._config.switchStrategy === 'preload-first') {\n void this.setLanguageAsync(id);\n return;\n }\n this.applyLanguage(id);\n }\n\n /** Preload-first switch: await the dictionary, then flip — no raw-key flash.\n * A failed load aborts: language, direction and dictionary stay untouched. */\n async setLanguageAsync(id: L): Promise<void> {\n if (id === this._currentLanguageId()) return;\n if (!this._languages().some((l) => l.id === id)) return;\n const { ok } = await this._loadTranslations(id, { silent: true });\n if (!ok) return;\n this.applyLanguage(id);\n }\n\n /** Number formatting bound to the current language locale (cached Intl). */\n formatNumber(value: number, options?: Intl.NumberFormatOptions): string {\n return this.numberFormatter(options).format(value);\n }\n\n /** Date/time formatting bound to the current language locale (cached Intl). */\n formatDate(value: Date | number, options?: Intl.DateTimeFormatOptions): string {\n return this.dateTimeFormatter(options).format(value);\n }\n\n /** BCP-47 locale driving Intl + ICU plural rules (falls back to the id). */\n readonly locale = computed<string>(() => {\n return this.currentLanguageObject().locale ?? this._currentLanguageId();\n });\n\n private readonly _formatters = new Map<string, Intl.NumberFormat | Intl.DateTimeFormat>();\n\n private numberFormatter(options?: Intl.NumberFormatOptions): Intl.NumberFormat {\n const key = `n|${this.locale()}|${JSON.stringify(options ?? null)}`;\n let formatter = this._formatters.get(key) as Intl.NumberFormat | undefined;\n if (!formatter) {\n formatter = new Intl.NumberFormat(this.locale(), options);\n this._formatters.set(key, formatter);\n }\n return formatter;\n }\n\n private dateTimeFormatter(options?: Intl.DateTimeFormatOptions): Intl.DateTimeFormat {\n const key = `d|${this.locale()}|${JSON.stringify(options ?? null)}`;\n let formatter = this._formatters.get(key) as Intl.DateTimeFormat | undefined;\n if (!formatter) {\n formatter = new Intl.DateTimeFormat(this.locale(), options);\n this._formatters.set(key, formatter);\n }\n return formatter;\n }\n\n private applyLanguage(id: L, opts?: { skipLoad?: boolean }): void {\n if (id === this._currentLanguageId()) return;\n\n const lang = this._languages().find((l) => l.id === id);\n if (!lang) return;\n\n this._applyCount++;\n\n const apply = () => this._currentLanguageId.set(id);\n const vt = this._config.viewTransition;\n const useTransition =\n vt?.enabled &&\n (!vt.skipInitialTransition || this._applyCount > 1) &&\n this._viewTransition != null;\n\n if (useTransition) {\n vt!.onViewTransitionCreated?.({ language: id, direction: lang.dir });\n this._viewTransition!.run(apply);\n } else {\n apply();\n }\n\n if (!opts?.skipLoad) {\n void this._loadTranslations(id);\n }\n }\n\n private render(template: string, params?: TranslateParams): string {\n if (!params) return template;\n if (!template.includes('{')) return template;\n try {\n return formatIcu(template, params, this.locale());\n } catch {\n return template;\n }\n }\n\n private async _loadTranslations(\n languageId: L,\n opts?: { silent?: boolean },\n ): Promise<{ data: Record<string, unknown>; ok: boolean }> {\n // A dictionary only ever reaches the visible signals when it belongs to\n // the currently intended language. Anything else (slow out-of-order\n // responses, explicit preloads of other languages) stays cached.\n const current = (): boolean => languageId === this._currentLanguageId();\n const cached = this._translationsCache.get(languageId);\n if (cached) {\n if (!opts?.silent && current()) {\n this._loadedTranslations.set(cached);\n }\n return { data: cached, ok: true };\n }\n\n const inflight = this._inflight.get(languageId);\n if (inflight) return inflight;\n\n this._loadingState.set('loading');\n\n const task: Promise<{ data: Record<string, unknown>; ok: boolean }> = (async () => {\n try {\n if (!this._resolvedLoader) {\n this._resolvedLoader = await this._getLoader!();\n }\n const translations = await this._resolvedLoader.load(languageId);\n\n this._translationsCache.set(languageId, translations);\n this.writeTransfer(languageId, translations);\n\n if (!opts?.silent && current()) {\n this._loadedTranslations.set(translations);\n this._loadingError.set(null);\n this._loadingState.set('idle');\n }\n\n return { data: translations, ok: true };\n } catch (error) {\n if (current()) {\n this._loadingError.set(error);\n this._loadingState.set('error');\n }\n this._config.onLoadError?.(languageId, error);\n return { data: {}, ok: false };\n } finally {\n this._inflight.delete(languageId);\n if (this._inflight.size === 0 && this._loadingState() === 'loading') {\n this._loadingState.set('idle');\n }\n }\n })();\n\n this._inflight.set(languageId, task);\n return task;\n }\n\n /**\n * Reads the persisted language. Cookie strategy: server reads the request\n * `Cookie` header (no hydration mismatch), browser reads `document.cookie`.\n * Everything else delegates to the SSR-safe storage helpers.\n */\n private _readStored(): string | null {\n if (this._storageStrategy === 'cookie') {\n const header = this._request?.headers.get('cookie') ?? null;\n if (header !== null) return parseCookie(header, this._storageKey);\n try {\n return parseCookie(this._doc.cookie, this._storageKey);\n } catch {\n return null;\n }\n }\n return safeGetItem(this._storageKey, this._storageStrategy);\n }\n\n /** Persists the language. Server never writes (response cookies are app-owned). */\n private _writeStored(id: L): void {\n if (this._storageStrategy === 'cookie') {\n if (this._request) return;\n try {\n const location = (\n this._doc as unknown as { location?: { protocol?: string; hostname?: string } }\n )?.location;\n this._doc.cookie = serializeCookie(this._storageKey, id, {\n secure: shouldSecureCookie(location),\n });\n } catch {\n // Best-effort persistence.\n }\n return;\n }\n safeSetItem(this._storageKey, id, this._storageStrategy);\n }\n\n private transferKey(languageId: L): StateKey<Record<string, unknown>> {\n return makeStateKey<Record<string, unknown>>(`rivinia.i18n.dict.${languageId}`);\n }\n\n /** Consumes server-rendered dictionaries so the client never refetches. */\n private readTransfer(languageId: L): Record<string, unknown> | null {\n const transfer = this._transfer;\n if (!transfer) return null;\n const key = this.transferKey(languageId);\n if (!transfer.hasKey(key)) return null;\n const dict = transfer.get(key, null);\n transfer.remove(key);\n return dict;\n }\n\n /** Stores freshly loaded dictionaries for hydration (server only). */\n private writeTransfer(languageId: L, dict: Record<string, unknown>): void {\n if (!this._request) return;\n this._transfer?.set(this.transferKey(languageId), dict);\n }\n\n private _resolveKey(obj: Record<string, unknown>, path: string): string | undefined {\n const value = path\n .split('.')\n .reduce<unknown>(\n (acc, segment) =>\n acc && typeof acc === 'object' ? (acc as Record<string, unknown>)[segment] : undefined,\n obj,\n );\n if (typeof value === 'string') return value;\n if (typeof value === 'number' || typeof value === 'boolean') return String(value);\n return undefined;\n }\n\n private _resolveInitialLanguage(): L {\n const stored = this._readStored();\n if (stored && this._config.languages.some((l) => l.id === stored)) {\n return stored as L;\n }\n if (this._config.detectBrowser) {\n const detected = detectBrowserLanguage(\n this._config.languages.map((l) => l.id),\n browserLanguages(),\n );\n if (detected) return detected;\n }\n return this._config.defaultLanguage;\n }\n}\n\nfunction normalizeKeyArgs(\n second?: string | TranslateParams,\n third?: TranslateParams,\n): { defaultValue?: string; params?: TranslateParams } {\n if (second && typeof second === 'object') {\n return { params: second };\n }\n return { defaultValue: second, params: third };\n}\n","import {\n EnvironmentProviders,\n inject,\n makeEnvironmentProviders,\n provideAppInitializer,\n} from '@angular/core';\nimport { RIVINIA_I18N_CONFIG, type RiviniaI18nConfig } from './i18n-config';\nimport { RiviniaI18n } from './rivinia-i18n';\n\n/**\n * Configures `@rivinia/i18n` for the application. Call once at bootstrap.\n * Also registers an app initializer that loads the initial language before\n * first paint (opt out with `preload: false`).\n *\n * @example\n * ```ts\n * provideRiviniaI18n({\n * defaultLanguage: 'ar',\n * languages: [\n * { id: 'ar', nativeName: 'العربية', dir: 'rtl' },\n * { id: 'en', nativeName: 'English', dir: 'ltr' },\n * ],\n * })\n * ```\n */\nexport function provideRiviniaI18n<L extends string>(\n config: RiviniaI18nConfig<L>,\n): EnvironmentProviders {\n return makeEnvironmentProviders([\n { provide: RIVINIA_I18N_CONFIG, useValue: config },\n provideAppInitializer(() => {\n const i18n = inject(RiviniaI18n) as RiviniaI18n<string>;\n return i18n.initialize();\n }),\n ]);\n}\n\n/** Shorthand for `inject(RiviniaI18n)` — preserves the configured language union. */\nexport function injectRiviniaI18n<L extends string = string>(): RiviniaI18n<L> {\n return inject(RiviniaI18n) as unknown as RiviniaI18n<L>;\n}\n\n/**\n * Binds a config and its typed accessors together so `L` is inferred once\n * from the configuration instead of being lost at the injection site.\n *\n * @example\n * ```ts\n * export const i18n = defineRiviniaI18n({\n * defaultLanguage: 'ar',\n * languages: [\n * { id: 'ar', nativeName: 'العربية', dir: 'rtl' },\n * { id: 'en', nativeName: 'English', dir: 'ltr' },\n * ],\n * });\n * // app.config.ts\n * providers: [i18n.provide()]\n * // anywhere (typed 'ar' | 'en'):\n * const lang = i18n.inject();\n * ```\n */\nexport function defineRiviniaI18n<L extends string>(config: RiviniaI18nConfig<L>): {\n readonly config: RiviniaI18nConfig<L>;\n provide: () => EnvironmentProviders;\n inject: () => RiviniaI18n<L>;\n} {\n return {\n config,\n provide: () => provideRiviniaI18n(config),\n inject: () => injectRiviniaI18n<L>(),\n };\n}\n","import { Pipe, inject } from '@angular/core';\nimport { RiviniaI18n } from './rivinia-i18n';\nimport type { TranslateParams } from './i18n-types';\nimport type { Translation } from './i18n-types';\n\n/**\n * Template pipe delegating to `RiviniaI18n.translate()`.\n *\n * Impure (`pure: false`) by necessity: the service reads signals on every\n * call, and a pure pipe would not re-evaluate on language switches. For long\n * lists prefer `translate()` in component code over this pipe.\n */\n@Pipe({\n name: 'rTranslate',\n pure: false,\n})\nexport class RTranslatePipe<L extends string = string> {\n private readonly _i18n = inject(RiviniaI18n<L>);\n\n transform(key: string, defaultValue?: string, params?: TranslateParams): string;\n transform(key: string, params?: TranslateParams): string;\n transform(translations: Translation<L>): string;\n\n transform(\n keyOrTranslations: string | Translation<L>,\n defaultValueOrParams?: string | TranslateParams,\n maybeParams?: TranslateParams,\n ): string {\n return this._i18n.translate(\n keyOrTranslations as string,\n defaultValueOrParams as string,\n maybeParams as TranslateParams,\n );\n }\n}\n"],"mappings":";;AAiBA,SAAgB,WAAW,SAA2B;CACpD,OAAO,EACL,MAAM,UAAO;EACX,MAAM,EAAE,eAAe,MAAM,OAAO;EACpC,OAAO,IAAI,WAAW,OAAO;CAC/B,EACD;AACH;AAQA,SAAgB,WAAW,SAA0B;CACnD,OAAO,EACL,MAAM,UAAO;EACX,MAAM,EAAE,eAAe,MAAM,OAAO;EACpC,OAAO,IAAI,WAAW,OAAO;CAC/B,EACD;AACH;AAOA,SAAgB,aAAa,SAA4B;CACvD,OAAO,EACL,MAAM,UAAO;EACX,MAAM,EAAE,iBAAiB,MAAM,OAAO;EACtC,OAAO,IAAI,aAAa,OAAO;CACjC,EACD;AACH;AAGA,SAAgB,aACd,MAAuD;CAEvD,OAAO,EACL,MAAM,UAAO;EACX,OAAO,EAAE,KAAI;CACf,EACD;AACH;AC9DA,SAAS,WAAW,UAAyB;CAI3C,IAAI,aAAa,UAAU,aAAa,UAAU,OAAO;CACzD,IAAI,OAAO,WAAW,aAAa,OAAO;CAC1C,IAAI;EACF,OAAO,aAAa,YAAY,OAAO,iBAAiB,OAAO;CACjE,QAAQ;EACN,OAAO;CACT;AACF;AAGA,SAAgB,YAAY,KAAa,UAAyB;CAChE,MAAM,UAAU,WAAW,QAAQ;CACnC,IAAI,CAAC,SAAS,OAAO;CACrB,IAAI;EACF,OAAO,QAAQ,QAAQ,GAAG;CAC5B,QAAQ;EACN,OAAO;CACT;AACF;AAGA,SAAgB,YAAY,KAAa,OAAe,UAAyB;CAC/E,MAAM,UAAU,WAA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AAC9C;ACxcA,SAAgB,mBACd,QAA4B;CAE5B,OAAO,yBAAyB,CAC9B;EAAE,SAAS;EAAqB,UAAU;CAAM,GAChD,4BAA2B;EAEzB,OADa,OAAO,WACb,CAAA,CAAK,WAAU;CACxB,CAAC,CACF,CAAA;AACH;AAGA,SAAgB,oBAAiB;CAC/B,OAAO,OAAO,WAAW;AAC3B;AAqBA,SAAgB,kBAAoC,QAA4B;CAK9E,OAAO;EACL;EACA,eAAe,mBAAmB,MAAM;EACxC,cAAc,kBAAiB;CAChC;AACH;ACvDA,IAAa,iBAAb,MAAa,eAAc;CACR,QAAQ,OAAO,WAAc;CAM9C,UACE,mBACA,sBACA,aAA6B;EAE7B,OAAO,KAAK,MAAM,UAChB,mBACA,sBACA,WAA8B;CAElC;CAjBW,OAAA,OAAA,GAAA,mBAAA;EAAA,YAAA;EAAA,SAAA;EAAA,UAAA;EAAA,MAAA;EAAc,MAAA,CAAA;EAAA,QAAA,GAAA,gBAAA;CAAA,CAAA;CAAd,OAAA,QAAA,GAAA,gBAAA;EAAA,YAAA;EAAA,SAAA;EAAA,UAAA;EAAA,MAAA;EAAc,cAAA;EAAA,MAAA;EAAA,MAAA;CAAA,CAAA;;AAAd,GAAA,yBAAA;CAAA,YAAA;CAAA,SAAA;CAAA,UAAA;CAAA,MAAA;CAAc,YAAA,CAAA;EAJ1B,MAAA;EAAK,MAAA,CAAA;GACJ,MAAM;GACN,MAAM;EACP,CAAA"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rivinia/i18n",
3
- "version": "0.2.0",
3
+ "version": "0.3.1",
4
4
  "description": "Headless language manager for Angular: signals, RTL, loaders, ICU plurals, browser detection, Intl formatting.",
5
5
  "keywords": [
6
6
  "angular",
@@ -27,6 +27,7 @@ const STARTER = (ids, detectBrowser) => {
27
27
  .join('\n');
28
28
  const detect = detectBrowser ? ',\n detectBrowser: true' : '';
29
29
  return (`provideRiviniaI18n({\n` +
30
+ ` // Dictionaries: public/i18n/{id}.json (default jsonLoader)\n` +
30
31
  ` defaultLanguage: '${ids[0]}',\n` +
31
32
  ` languages: [\n${languages}\n ],${detect}\n` +
32
33
  ` })`);
@@ -6,7 +6,7 @@
6
6
  "properties": {
7
7
  "languages": {
8
8
  "type": "string",
9
- "description": "Comma-separated language ids — bare (ar, en), quoted ('ar', 'en') or bracketed ([ar, en]). First id becomes the default language.",
9
+ "description": "Comma-separated language ids — bare (ar, en), quoted ('ar', 'en') or bracketed ([ar, en]). First id becomes the default language. Dictionaries load from public/i18n/{id}.json by default.",
10
10
  "x-prompt": {
11
11
  "message": "Language ids for this project (ar, en — brackets and quotes also fine)?",
12
12
  "type": "input"
@@ -78,7 +78,8 @@ interface RiviniaI18nConfig<T extends string = string> {
78
78
  readonly viewTransition?: ViewTransitionConfig;
79
79
  /**
80
80
  * Dictionary source. Defaults to `jsonLoader()` — the conventional
81
- * `assets/i18n/{language}.json` layout. Override with any descriptor
81
+ * `i18n/{language}.json` layout (files in `public/i18n/`, served from the
82
+ * site root). Override with any descriptor
82
83
  * (custom path, HTTP endpoint, in-memory). Inline-only apps that want zero
83
84
  * network traffic pass `customLoader(async () => ({}))`.
84
85
  */
@@ -133,8 +134,20 @@ export declare function browserLanguages(): readonly string[] | undefined;
133
134
  */
134
135
  /** Extracts a cookie value by name from a `Cookie` header or `document.cookie`. */
135
136
  export declare function parseCookie(header: string | null | undefined, name: string): string | null;
136
- /** Serializes a language cookie ( Lax, root path, one year). */
137
- export declare function serializeCookie(name: string, value: string): string;
137
+ /** Serializes a language cookie (Lax, root path, one year). */
138
+ export declare function serializeCookie(name: string, value: string, options?: {
139
+ secure?: boolean;
140
+ }): string;
141
+ /**
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).
146
+ */
147
+ declare function shouldSecureCookie(location: {
148
+ protocol?: string;
149
+ hostname?: string;
150
+ } | null | undefined): boolean;
138
151
  /**
139
152
  * Minimal ICU MessageFormat subset: `{name}` interpolation, `{n, plural, …}`,
140
153
  * `{x, select, …}`, `#` inside plurals, and nesting. Categories resolve via
@@ -175,7 +188,8 @@ export declare class RiviniaI18n<L extends string = string> {
175
188
  private readonly _loadedTranslations;
176
189
  /**
177
190
  * Explicit loader wins; otherwise the conventional JSON layout
178
- * (`assets/i18n/{language}.json` unless the consumer overrides the path).
191
+ * (`i18n/{language}.json` — files in `public/i18n/`, served from the site
192
+ * root — unless the consumer overrides the path).
179
193
  * The descriptor still code-splits: the fetch implementation loads only on
180
194
  * first resolve.
181
195
  */
@@ -312,7 +326,6 @@ export declare function defineRiviniaI18n<L extends string>(config: RiviniaI18nC
312
326
  /** Progressive-enhancement wrapper around the View Transition API. */
313
327
  export declare class ViewTransitionService {
314
328
  private readonly _doc;
315
- private get _supported();
316
329
  run(callback: () => void): void;
317
330
  static ɵfac: i0.ɵɵFactoryDeclaration<ViewTransitionService, never>;
318
331
  static ɵprov: i0.ɵɵInjectableDeclaration<any>;
@@ -1 +0,0 @@
1
- {"version":3,"file":"rivinia-i18n-json-loader.impl-CGzkWfF_.mjs","names":[],"sources":["../../../projects/i18n/src/lib/json-loader.impl.ts"],"sourcesContent":["import type { TranslationLoader } from './loaders';\n\nconst DEFAULT_BASE_PATH = 'assets/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"}