@rivinia/i18n 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -7,7 +7,7 @@ Headless language manager for Angular 22+. Signals, RTL/LTR, lazy loaders,
7
7
  ICU plurals (all six Arabic forms), browser detection, Intl formatting —
8
8
  zero DOM opinions beyond `<html dir/lang>`, zero styling.
9
9
 
10
- - Version: **0.1.1**
10
+ - Version: **0.2.0**
11
11
  - Requires: **Angular `^22.0.0`**, `tslib`
12
12
 
13
13
  ## Install
@@ -37,6 +37,33 @@ provideRiviniaI18n({ loader: httpLoader({ endpoint: 'https://api.example.com/i18
37
37
 
38
38
  Loaders code-split: fetch implementations load on first use only.
39
39
 
40
+ ## Startup loading (no raw keys on first paint)
41
+
42
+ `provideRiviniaI18n()` registers an app initializer that loads the initial
43
+ language before first paint (SSR waits via `PendingTasks`):
44
+
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
+ ```
52
+
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.
56
+
57
+ ## Persistence and SSR
58
+
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.
66
+
40
67
  ```ts
41
68
  // app.config.ts
42
69
  import { provideRiviniaI18n } from '@rivinia/i18n';
@@ -76,16 +103,20 @@ export class Header {
76
103
 
77
104
  | Export | Kind | Purpose |
78
105
  |---|---|---|
79
- | `provideRiviniaI18n(config)` | provider | languages, default, storage, loader, `detectBrowser?` (off), `switchStrategy?` |
80
- | `RiviniaI18n` | `@Service()` | signals + `translate/setLanguage(toggle/next/previous)/loadTranslations/formatNumber/formatDate` |
81
- | `injectRiviniaI18n()` | function | shorthand for `inject(RiviniaI18n)` |
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 |
82
109
  | `jsonLoader/httpLoader/remoteLoader/customLoader` | loaders | lazy code-split dictionaries (fetch, no HttpClient) |
83
110
  | `formatIcu(template, params, locale)` | util | ICU subset: plural/select/`#`/nesting via native `Intl.PluralRules` |
84
- | `detectBrowserLanguage(ids, langs)` | util | priority match + base-tag fallback (`ar-EG` → `ar`), pure/testable |
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) |
85
113
  | `RTranslatePipe` | pipe | `rTranslate` (impure by necessity — prefer `translate()` in code for lists) |
86
- | types | types | `RiviniaI18nConfig`, `Language`, `Translation`, `LoaderDescriptor`, … |
114
+ | types | types | `RiviniaI18nConfig`, `Language` (+`locale?`), `Translation`, `LoaderDescriptor`, … |
87
115
 
88
- ICU subset is deliberately small (`plural`/`select` only) — full ICU belongs to
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
89
120
  FormatJS, not to a 10 kB core. Malformed templates render raw, never throw.
90
121
  Stored preference always beats browser detection; detection runs only when
91
122
  nothing is stored. `switchStrategy: 'preload-first'` (or `setLanguageAsync`)
@@ -1,5 +1,5 @@
1
1
  import * as i0 from "@angular/core";
2
- import { InjectionToken, Pipe, Service, computed, effect, inject, makeEnvironmentProviders, signal } from "@angular/core";
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
5
  const { JsonLoader } = await import("./rivinia-i18n-json-loader.impl-CGzkWfF_.mjs");
@@ -24,7 +24,7 @@ function customLoader(load) {
24
24
  } };
25
25
  }
26
26
  function getStorage(strategy) {
27
- if (strategy === "none") return null;
27
+ if (strategy === "none" || strategy === "cookie") return null;
28
28
  if (typeof window === "undefined") return null;
29
29
  try {
30
30
  return strategy === "session" ? window.sessionStorage : window.localStorage;
@@ -56,12 +56,11 @@ function detectBrowserLanguage(supportedIds, browserLanguages) {
56
56
  if (!tag) continue;
57
57
  const exact = supported.indexOf(tag);
58
58
  if (exact !== -1) return supportedIds[exact];
59
- }
60
- for (const raw of browserLanguages) {
61
- const base = raw.trim().toLowerCase().split(/[-_]/)[0];
62
- if (!base) continue;
63
- const hit = supported.indexOf(base);
64
- if (hit !== -1) return supportedIds[hit];
59
+ const base = tag.split(/[-_]/)[0];
60
+ if (base && base !== tag) {
61
+ const hit = supported.indexOf(base);
62
+ if (hit !== -1) return supportedIds[hit];
63
+ }
65
64
  }
66
65
  return null;
67
66
  }
@@ -74,6 +73,22 @@ function browserLanguages() {
74
73
  return;
75
74
  }
76
75
  }
76
+ function parseCookie(header, name) {
77
+ if (!header) return null;
78
+ const prefix = `${name}=`;
79
+ for (const part of header.split(";")) {
80
+ const trimmed = part.trim();
81
+ if (trimmed.startsWith(prefix)) try {
82
+ return decodeURIComponent(trimmed.slice(prefix.length));
83
+ } catch {
84
+ return trimmed.slice(prefix.length);
85
+ }
86
+ }
87
+ return null;
88
+ }
89
+ function serializeCookie(name, value) {
90
+ return `${name}=${encodeURIComponent(value)}; Path=/; Max-Age=31536000; SameSite=Lax`;
91
+ }
77
92
  function formatIcu(template, params, locale) {
78
93
  return parseMessage(template, 0, template.length, params, locale, null).text;
79
94
  }
@@ -262,9 +277,17 @@ function readSelector(src, i, end) {
262
277
  }
263
278
  const RIVINIA_I18N_CONFIG = new InjectionToken("RIVINIA_I18N_CONFIG");
264
279
  var ViewTransitionService = class ViewTransitionService {
265
- _supported = typeof document !== "undefined" && typeof document.startViewTransition === "function";
280
+ _doc = inject(DOCUMENT);
281
+ get _supported() {
282
+ try {
283
+ return typeof this._doc.startViewTransition === "function";
284
+ } catch {
285
+ return false;
286
+ }
287
+ }
266
288
  run(callback) {
267
- if (this._supported) document.startViewTransition(callback);
289
+ const doc = this._doc;
290
+ if (typeof doc.startViewTransition === "function") doc.startViewTransition(callback);
268
291
  else callback();
269
292
  }
270
293
  static ɵfac = i0.ɵɵngDeclareFactory({
@@ -295,6 +318,9 @@ var RiviniaI18n = class RiviniaI18n {
295
318
  _storageKey = this._config.storageKey ?? "rivinia.i18n.language";
296
319
  _storageStrategy = this._config.storageStrategy ?? "local";
297
320
  _autoApplyDirection = this._config.autoApplyDirection ?? true;
321
+ _doc = inject(DOCUMENT);
322
+ _request = inject(REQUEST, { optional: true });
323
+ _transfer = inject(TransferState, { optional: true });
298
324
  _currentLanguageId = signal(this._resolveInitialLanguage(), ...ngDevMode ? [{ debugName: "_currentLanguageId" }] : /* istanbul ignore next */ []);
299
325
  _languages = signal(this._config.languages, ...ngDevMode ? [{ debugName: "_languages" }] : /* istanbul ignore next */ []);
300
326
  _loadedTranslations = signal({}, ...ngDevMode ? [{ debugName: "_loadedTranslations" }] : /* istanbul ignore next */ []);
@@ -302,8 +328,9 @@ var RiviniaI18n = class RiviniaI18n {
302
328
  _resolvedLoader = null;
303
329
  _translationsCache = /* @__PURE__ */ new Map();
304
330
  _inflight = /* @__PURE__ */ new Map();
305
- _requestToken = 0;
306
331
  _applyCount = 0;
332
+ _initialized = false;
333
+ _tasks = inject(PendingTasks, { optional: true });
307
334
  languageChanged = computed(() => this._currentLanguageId(), ...ngDevMode ? [{ debugName: "languageChanged" }] : /* istanbul ignore next */ []);
308
335
  languages = this._languages.asReadonly();
309
336
  currentLanguage = this._currentLanguageId.asReadonly();
@@ -318,23 +345,46 @@ var RiviniaI18n = class RiviniaI18n {
318
345
  loadingState = this._loadingState.asReadonly();
319
346
  loadingError = this._loadingError.asReadonly();
320
347
  isLoading = computed(() => this._loadingState() === "loading", ...ngDevMode ? [{ debugName: "isLoading" }] : /* istanbul ignore next */ []);
348
+ _ready = signal(false, ...ngDevMode ? [{ debugName: "_ready" }] : /* istanbul ignore next */ []);
349
+ ready = this._ready.asReadonly();
321
350
  constructor() {
322
351
  if (this._config.languages.length === 0) throw new Error("[rivinia/i18n] At least one language must be provided in the languages array.");
323
352
  if (!this._config.languages.some((l) => l.id === this._config.defaultLanguage)) throw new Error(`[rivinia/i18n] defaultLanguage "${this._config.defaultLanguage}" must be one of the configured language IDs.`);
324
353
  effect(() => {
325
354
  const id = this._currentLanguageId();
326
- safeSetItem(this._storageKey, id, this._storageStrategy);
355
+ this._writeStored(id);
327
356
  });
328
357
  if (this._autoApplyDirection) effect(() => {
329
- if (typeof document === "undefined") return;
330
358
  const lang = this.currentLanguageObject();
331
- document.documentElement.dir = lang.dir;
332
- document.documentElement.lang = lang.id;
359
+ const root = this._doc.documentElement;
360
+ if (!root) return;
361
+ root.dir = lang.dir;
362
+ root.lang = lang.id;
333
363
  });
334
364
  }
335
365
  getLanguage(id) {
336
366
  return this._languages().find((l) => l.id === id);
337
367
  }
368
+ async initialize() {
369
+ if (this._initialized) return;
370
+ this._initialized = true;
371
+ const done = this._tasks?.add();
372
+ try {
373
+ const current = this._currentLanguageId();
374
+ const transferred = this.readTransfer(current);
375
+ if (transferred) {
376
+ this._translationsCache.set(current, transferred);
377
+ this._loadedTranslations.set(transferred);
378
+ } else {
379
+ const inline = this._config.translations?.[current];
380
+ if (inline) this._loadedTranslations.set(inline);
381
+ if (this._config.preload ?? true) await this._loadTranslations(current);
382
+ }
383
+ } finally {
384
+ this._ready.set(true);
385
+ done?.();
386
+ }
387
+ }
338
388
  translate(keyOrTranslations, defaultValueOrParams, maybeParams) {
339
389
  if (typeof keyOrTranslations === "string") {
340
390
  const { defaultValue, params } = normalizeKeyArgs(defaultValueOrParams, maybeParams);
@@ -348,7 +398,7 @@ var RiviniaI18n = class RiviniaI18n {
348
398
  }
349
399
  loadedTranslations = this._loadedTranslations.asReadonly();
350
400
  async loadTranslations(languageId, opts) {
351
- return this._loadTranslations(languageId, opts);
401
+ return (await this._loadTranslations(languageId, opts)).data;
352
402
  }
353
403
  toggle() {
354
404
  const langs = this._languages();
@@ -378,14 +428,37 @@ var RiviniaI18n = class RiviniaI18n {
378
428
  async setLanguageAsync(id) {
379
429
  if (id === this._currentLanguageId()) return;
380
430
  if (!this._languages().some((l) => l.id === id)) return;
381
- await this._loadTranslations(id, { silent: true });
431
+ const { ok } = await this._loadTranslations(id, { silent: true });
432
+ if (!ok) return;
382
433
  this.applyLanguage(id);
383
434
  }
384
435
  formatNumber(value, options) {
385
- return new Intl.NumberFormat(this._currentLanguageId(), options).format(value);
436
+ return this.numberFormatter(options).format(value);
386
437
  }
387
438
  formatDate(value, options) {
388
- return new Intl.DateTimeFormat(this._currentLanguageId(), options).format(value);
439
+ return this.dateTimeFormatter(options).format(value);
440
+ }
441
+ locale = computed(() => {
442
+ return this.currentLanguageObject().locale ?? this._currentLanguageId();
443
+ }, ...ngDevMode ? [{ debugName: "locale" }] : /* istanbul ignore next */ []);
444
+ _formatters = /* @__PURE__ */ new Map();
445
+ numberFormatter(options) {
446
+ const key = `n|${this.locale()}|${JSON.stringify(options ?? null)}`;
447
+ let formatter = this._formatters.get(key);
448
+ if (!formatter) {
449
+ formatter = new Intl.NumberFormat(this.locale(), options);
450
+ this._formatters.set(key, formatter);
451
+ }
452
+ return formatter;
453
+ }
454
+ dateTimeFormatter(options) {
455
+ const key = `d|${this.locale()}|${JSON.stringify(options ?? null)}`;
456
+ let formatter = this._formatters.get(key);
457
+ if (!formatter) {
458
+ formatter = new Intl.DateTimeFormat(this.locale(), options);
459
+ this._formatters.set(key, formatter);
460
+ }
461
+ return formatter;
389
462
  }
390
463
  applyLanguage(id, opts) {
391
464
  if (id === this._currentLanguageId()) return;
@@ -407,39 +480,49 @@ var RiviniaI18n = class RiviniaI18n {
407
480
  if (!params) return template;
408
481
  if (!template.includes("{")) return template;
409
482
  try {
410
- return formatIcu(template, params, this._currentLanguageId());
483
+ return formatIcu(template, params, this.locale());
411
484
  } catch {
412
485
  return template;
413
486
  }
414
487
  }
415
488
  async _loadTranslations(languageId, opts) {
489
+ const current = () => languageId === this._currentLanguageId();
416
490
  const cached = this._translationsCache.get(languageId);
417
491
  if (cached) {
418
- if (!opts?.silent) this._loadedTranslations.set(cached);
419
- return cached;
492
+ if (!opts?.silent && current()) this._loadedTranslations.set(cached);
493
+ return {
494
+ data: cached,
495
+ ok: true
496
+ };
420
497
  }
421
498
  const inflight = this._inflight.get(languageId);
422
499
  if (inflight) return inflight;
423
- const myToken = ++this._requestToken;
424
500
  this._loadingState.set("loading");
425
501
  const task = (async () => {
426
502
  try {
427
503
  if (!this._resolvedLoader) this._resolvedLoader = await this._getLoader();
428
504
  const translations = await this._resolvedLoader.load(languageId);
429
505
  this._translationsCache.set(languageId, translations);
430
- if (myToken === this._requestToken && !opts?.silent) {
506
+ this.writeTransfer(languageId, translations);
507
+ if (!opts?.silent && current()) {
431
508
  this._loadedTranslations.set(translations);
432
509
  this._loadingError.set(null);
433
510
  this._loadingState.set("idle");
434
511
  }
435
- return translations;
512
+ return {
513
+ data: translations,
514
+ ok: true
515
+ };
436
516
  } catch (error) {
437
- if (myToken === this._requestToken) {
517
+ if (current()) {
438
518
  this._loadingError.set(error);
439
519
  this._loadingState.set("error");
440
520
  }
441
521
  this._config.onLoadError?.(languageId, error);
442
- return {};
522
+ return {
523
+ data: {},
524
+ ok: false
525
+ };
443
526
  } finally {
444
527
  this._inflight.delete(languageId);
445
528
  if (this._inflight.size === 0 && this._loadingState() === "loading") this._loadingState.set("idle");
@@ -448,13 +531,51 @@ var RiviniaI18n = class RiviniaI18n {
448
531
  this._inflight.set(languageId, task);
449
532
  return task;
450
533
  }
534
+ _readStored() {
535
+ if (this._storageStrategy === "cookie") {
536
+ const header = this._request?.headers.get("cookie") ?? null;
537
+ if (header !== null) return parseCookie(header, this._storageKey);
538
+ try {
539
+ return parseCookie(this._doc.cookie, this._storageKey);
540
+ } catch {
541
+ return null;
542
+ }
543
+ }
544
+ return safeGetItem(this._storageKey, this._storageStrategy);
545
+ }
546
+ _writeStored(id) {
547
+ if (this._storageStrategy === "cookie") {
548
+ if (this._request) return;
549
+ try {
550
+ this._doc.cookie = serializeCookie(this._storageKey, id);
551
+ } catch {}
552
+ return;
553
+ }
554
+ safeSetItem(this._storageKey, id, this._storageStrategy);
555
+ }
556
+ transferKey(languageId) {
557
+ return makeStateKey(`rivinia.i18n.dict.${languageId}`);
558
+ }
559
+ readTransfer(languageId) {
560
+ const transfer = this._transfer;
561
+ if (!transfer) return null;
562
+ const key = this.transferKey(languageId);
563
+ if (!transfer.hasKey(key)) return null;
564
+ const dict = transfer.get(key, null);
565
+ transfer.remove(key);
566
+ return dict;
567
+ }
568
+ writeTransfer(languageId, dict) {
569
+ if (!this._request) return;
570
+ this._transfer?.set(this.transferKey(languageId), dict);
571
+ }
451
572
  _resolveKey(obj, path) {
452
573
  const value = path.split(".").reduce((acc, segment) => acc && typeof acc === "object" ? acc[segment] : void 0, obj);
453
574
  if (typeof value === "string") return value;
454
575
  if (typeof value === "number" || typeof value === "boolean") return String(value);
455
576
  }
456
577
  _resolveInitialLanguage() {
457
- const stored = safeGetItem(this._storageKey, this._storageStrategy);
578
+ const stored = this._readStored();
458
579
  if (stored && this._config.languages.some((l) => l.id === stored)) return stored;
459
580
  if (this._config.detectBrowser) {
460
581
  const detected = detectBrowserLanguage(this._config.languages.map((l) => l.id), browserLanguages());
@@ -496,11 +617,20 @@ function provideRiviniaI18n(config) {
496
617
  return makeEnvironmentProviders([{
497
618
  provide: RIVINIA_I18N_CONFIG,
498
619
  useValue: config
499
- }]);
620
+ }, provideAppInitializer(() => {
621
+ return inject(RiviniaI18n).initialize();
622
+ })]);
500
623
  }
501
624
  function injectRiviniaI18n() {
502
625
  return inject(RiviniaI18n);
503
626
  }
627
+ function defineRiviniaI18n(config) {
628
+ return {
629
+ config,
630
+ provide: () => provideRiviniaI18n(config),
631
+ inject: () => injectRiviniaI18n()
632
+ };
633
+ }
504
634
  var RTranslatePipe = class RTranslatePipe {
505
635
  _i18n = inject(RiviniaI18n);
506
636
  transform(keyOrTranslations, defaultValueOrParams, maybeParams) {
@@ -538,6 +668,6 @@ i0.ɵɵngDeclareClassMetadata({
538
668
  }]
539
669
  }]
540
670
  });
541
- export { RTranslatePipe, RiviniaI18n, ViewTransitionService, browserLanguages, customLoader, detectBrowserLanguage, formatIcu, httpLoader, injectRiviniaI18n, jsonLoader, provideRiviniaI18n, remoteLoader };
671
+ export { RTranslatePipe, RiviniaI18n, ViewTransitionService, browserLanguages, customLoader, defineRiviniaI18n, detectBrowserLanguage, formatIcu, httpLoader, injectRiviniaI18n, jsonLoader, parseCookie, provideRiviniaI18n, remoteLoader, serializeCookie };
542
672
 
543
673
  //# sourceMappingURL=rivinia-i18n.mjs.map
@@ -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/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 if (strategy === 'none') 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.\n * Exact (case-insensitive) matches win first; otherwise base tags match\n * (`ar-EG` → `ar`). Returns `null` when nothing matches or off-browser.\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 }\n for (const raw of browserLanguages) {\n const base = raw.trim().toLowerCase().split(/[-_]/)[0];\n if (!base) continue;\n const hit = supported.indexOf(base);\n if (hit !== -1) return supportedIds[hit];\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","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 * 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 { Service } from '@angular/core';\n\n/** Progressive-enhancement wrapper around the View Transition API. */\n@Service()\nexport class ViewTransitionService {\n private readonly _supported =\n typeof document !== 'undefined' && typeof document.startViewTransition === 'function';\n\n run(callback: () => void): void {\n if (this._supported) {\n document.startViewTransition(callback);\n } else {\n callback();\n }\n }\n}\n","import { Service, computed, effect, inject, signal } 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 { 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 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<Record<string, unknown>>>();\n /**\n * Last-request-wins guard for rapid switches: each load captures a token;\n * stale out-of-order responses stay cached but never overwrite the signal.\n */\n private _requestToken = 0;\n private _applyCount = 0;\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 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 safeSetItem(this._storageKey, id, this._storageStrategy);\n });\n\n if (this._autoApplyDirection) {\n effect(() => {\n if (typeof document === 'undefined') {\n return;\n }\n const lang = this.currentLanguageObject();\n document.documentElement.dir = lang.dir;\n document.documentElement.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 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 this._loadTranslations(languageId, opts);\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 async setLanguageAsync(id: L): Promise<void> {\n if (id === this._currentLanguageId()) return;\n if (!this._languages().some((l) => l.id === id)) return;\n await this._loadTranslations(id, { silent: true });\n this.applyLanguage(id);\n }\n\n /** Number formatting bound to the current language (pure Intl wrapper). */\n formatNumber(value: number, options?: Intl.NumberFormatOptions): string {\n return new Intl.NumberFormat(this._currentLanguageId(), options).format(value);\n }\n\n /** Date/time formatting bound to the current language (pure Intl wrapper). */\n formatDate(value: Date | number, options?: Intl.DateTimeFormatOptions): string {\n return new Intl.DateTimeFormat(this._currentLanguageId(), options).format(value);\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._currentLanguageId());\n } catch {\n return template;\n }\n }\n\n private async _loadTranslations(\n languageId: L,\n opts?: { silent?: boolean },\n ): Promise<Record<string, unknown>> {\n const cached = this._translationsCache.get(languageId);\n if (cached) {\n if (!opts?.silent) {\n this._loadedTranslations.set(cached);\n }\n return cached;\n }\n\n const inflight = this._inflight.get(languageId);\n if (inflight) return inflight;\n\n const myToken = ++this._requestToken;\n this._loadingState.set('loading');\n\n const task = (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\n if (myToken === this._requestToken && !opts?.silent) {\n this._loadedTranslations.set(translations);\n this._loadingError.set(null);\n this._loadingState.set('idle');\n }\n\n return translations;\n } catch (error) {\n if (myToken === this._requestToken) {\n this._loadingError.set(error);\n this._loadingState.set('error');\n }\n this._config.onLoadError?.(languageId, error);\n return {};\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 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 = safeGetItem(this._storageKey, this._storageStrategy);\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 { EnvironmentProviders, inject, makeEnvironmentProviders } 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 *\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([{ provide: RIVINIA_I18N_CONFIG, useValue: config }]);\n}\n\n/** Shorthand for `inject(RiviniaI18n)`. */\nexport function injectRiviniaI18n(): RiviniaI18n<string> {\n return inject(RiviniaI18n);\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,WAA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,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(\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;CAC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AAA"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rivinia/i18n",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "description": "Headless language manager for Angular: signals, RTL, loaders, ICU plurals, browser detection, Intl formatting.",
5
5
  "keywords": [
6
6
  "angular",
@@ -10,11 +10,18 @@ interface Language<T extends string = string> {
10
10
  readonly id: T;
11
11
  readonly nativeName?: string;
12
12
  readonly dir: Direction;
13
+ /**
14
+ * BCP-47 locale for `Intl` formatting and plural rules (e.g. `ar-EG` for
15
+ * Arabic-Indic digits, `en-GB` vs `en-US`). Defaults to the language id —
16
+ * note a bare id like `ar` formats Latin digits, which is often NOT what
17
+ * Arabic readers expect.
18
+ */
19
+ readonly locale?: string;
13
20
  }
14
21
  /** Inline typed translations: `{ ar: 'حفظ', en: 'Save' }`. */
15
22
  type Translation<T extends string> = Record<T, string>;
16
23
  /** Persistence backend. SSR-safe: everything degrades to no-op off-browser. */
17
- type StorageStrategy = 'local' | 'session' | 'none';
24
+ type StorageStrategy = 'local' | 'session' | 'none' | 'cookie';
18
25
  /** Interpolation + ICU params (`{count}`, `{gender}`). */
19
26
  type TranslateParams = Record<string, string | number | boolean>;
20
27
  interface ViewTransitionInfo {
@@ -79,6 +86,18 @@ interface RiviniaI18nConfig<T extends string = string> {
79
86
  readonly switchStrategy?: SwitchStrategy;
80
87
  /** Called when a dictionary load fails. The service still falls back safely. */
81
88
  readonly onLoadError?: (language: T, error: unknown) => void;
89
+ /**
90
+ * Load the initial language during provider setup (before first paint).
91
+ * SSR waits via `PendingTasks`. Set `false` to skip (e.g. fully inline apps
92
+ * that call `loadTranslations` themselves).
93
+ * @default true
94
+ */
95
+ readonly preload?: boolean;
96
+ /**
97
+ * Inline per-language dictionaries. Seeded before any network load (zero
98
+ * network + SSR-safe first paint); a successful loader response still wins.
99
+ */
100
+ readonly translations?: Partial<Record<T, Record<string, unknown>>>;
82
101
  /**
83
102
  * Match `navigator.languages` against supported ids on first visit
84
103
  * (stored preference always wins; base tags match, e.g. `ar-EG` → `ar`).
@@ -99,14 +118,23 @@ declare function safeGetItem(key: string, strategy: StorageStrategy): string | n
99
118
  /** SSR-safe write. Silently no-ops off-browser or on denial. */
100
119
  declare function safeSetItem(key: string, value: string, strategy: StorageStrategy): void;
101
120
  /**
102
- * Matches the browser language priority list against supported ids.
103
- * Exact (case-insensitive) matches win first; otherwise base tags match
104
- * (`ar-EG` → `ar`). Returns `null` when nothing matches or off-browser.
121
+ * Matches the browser language priority list against supported ids, in order.
122
+ * For each browser entry (highest preference first) tries the exact tag, then
123
+ * its base subtag (`ar-EG` → `ar`). Returns the first hit, or `null`.
105
124
  * Pure and exported for testing — pass `navigator.languages` in app code.
106
125
  */
107
126
  export declare function detectBrowserLanguage<T extends string>(supportedIds: readonly T[], browserLanguages: readonly string[] | undefined): T | null;
108
127
  /** Browser language list, `undefined` off-browser (SSR-safe input for detection). */
109
128
  export declare function browserLanguages(): readonly string[] | undefined;
129
+ /**
130
+ * Cookie helpers for the `'cookie'` storage strategy. Pure and SSR-testable:
131
+ * the service supplies the header (server `REQUEST`) or `document.cookie`
132
+ * (browser); these functions only parse and serialize.
133
+ */
134
+ /** Extracts a cookie value by name from a `Cookie` header or `document.cookie`. */
135
+ 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;
110
138
  /**
111
139
  * Minimal ICU MessageFormat subset: `{name}` interpolation, `{n, plural, …}`,
112
140
  * `{x, select, …}`, `#` inside plurals, and nesting. Categories resolve via
@@ -133,6 +161,15 @@ export declare class RiviniaI18n<L extends string = string> {
133
161
  private readonly _storageKey;
134
162
  private readonly _storageStrategy;
135
163
  private readonly _autoApplyDirection;
164
+ /**
165
+ * Injected (not global) document: the dir/lang effect renders on the
166
+ * server too, avoiding an RTL first-paint shift on hydration.
167
+ * Declared before any field initializer that reads storage.
168
+ */
169
+ private readonly _doc;
170
+ /** Present only on the server: used for cookie reads + transfer writes. */
171
+ private readonly _request;
172
+ private readonly _transfer;
136
173
  private readonly _currentLanguageId;
137
174
  private readonly _languages;
138
175
  private readonly _loadedTranslations;
@@ -147,11 +184,14 @@ export declare class RiviniaI18n<L extends string = string> {
147
184
  private readonly _translationsCache;
148
185
  private readonly _inflight;
149
186
  /**
150
- * Last-request-wins guard for rapid switches: each load captures a token;
151
- * stale out-of-order responses stay cached but never overwrite the signal.
187
+ * Out-of-order safety: a response reaches the visible signals only when it
188
+ * belongs to the currently intended language (`_currentLanguageId()`).
189
+ * Everything else stays cached. (A monotonic request token used to guard
190
+ * this, but it over-constrained legitimate same-language loads.)
152
191
  */
153
- private _requestToken;
154
192
  private _applyCount;
193
+ private _initialized;
194
+ private readonly _tasks;
155
195
  readonly languageChanged: import("@angular/core").Signal<L>;
156
196
  readonly languages: import("@angular/core").Signal<readonly Language<L>[]>;
157
197
  readonly currentLanguage: import("@angular/core").Signal<L>;
@@ -164,8 +204,23 @@ export declare class RiviniaI18n<L extends string = string> {
164
204
  readonly loadingState: import("@angular/core").Signal<"idle" | "loading" | "error">;
165
205
  readonly loadingError: import("@angular/core").Signal<unknown>;
166
206
  readonly isLoading: import("@angular/core").Signal<boolean>;
207
+ private readonly _ready;
208
+ /**
209
+ * True once the initial language content is available (inline seed and/or
210
+ * initial load settled) — or immediately when `preload: false` skips setup
211
+ * loading. Gate first-paint skeletons on this, not on `isLoading`.
212
+ */
213
+ readonly ready: import("@angular/core").Signal<boolean>;
167
214
  constructor();
168
215
  getLanguage(id: L): Language<L> | undefined;
216
+ /**
217
+ * Runs the provider-setup loading: seeds inline dictionaries, then loads
218
+ * the initial language (unless `preload: false`). Called automatically by
219
+ * the `provideRiviniaI18n` app initializer; call manually only when driving
220
+ * setup yourself. Idempotent. Never rejects (load failures land on
221
+ * `loadingError`/`onLoadError`, inline seeds are preserved).
222
+ */
223
+ initialize(): Promise<void>;
169
224
  translate(key: string, defaultValue?: string, params?: TranslateParams): string;
170
225
  translate(key: string, params?: TranslateParams): string;
171
226
  translate(translations: Translation<L>): string;
@@ -178,15 +233,34 @@ export declare class RiviniaI18n<L extends string = string> {
178
233
  next(): void;
179
234
  previous(): void;
180
235
  setLanguage(id: L): void;
181
- /** Preload-first switch: await the dictionary, then flip — no raw-key flash. */
236
+ /** Preload-first switch: await the dictionary, then flip — no raw-key flash.
237
+ * A failed load aborts: language, direction and dictionary stay untouched. */
182
238
  setLanguageAsync(id: L): Promise<void>;
183
- /** Number formatting bound to the current language (pure Intl wrapper). */
239
+ /** Number formatting bound to the current language locale (cached Intl). */
184
240
  formatNumber(value: number, options?: Intl.NumberFormatOptions): string;
185
- /** Date/time formatting bound to the current language (pure Intl wrapper). */
241
+ /** Date/time formatting bound to the current language locale (cached Intl). */
186
242
  formatDate(value: Date | number, options?: Intl.DateTimeFormatOptions): string;
243
+ /** BCP-47 locale driving Intl + ICU plural rules (falls back to the id). */
244
+ readonly locale: import("@angular/core").Signal<string>;
245
+ private readonly _formatters;
246
+ private numberFormatter;
247
+ private dateTimeFormatter;
187
248
  private applyLanguage;
188
249
  private render;
189
250
  private _loadTranslations;
251
+ /**
252
+ * Reads the persisted language. Cookie strategy: server reads the request
253
+ * `Cookie` header (no hydration mismatch), browser reads `document.cookie`.
254
+ * Everything else delegates to the SSR-safe storage helpers.
255
+ */
256
+ private _readStored;
257
+ /** Persists the language. Server never writes (response cookies are app-owned). */
258
+ private _writeStored;
259
+ private transferKey;
260
+ /** Consumes server-rendered dictionaries so the client never refetches. */
261
+ private readTransfer;
262
+ /** Stores freshly loaded dictionaries for hydration (server only). */
263
+ private writeTransfer;
190
264
  private _resolveKey;
191
265
  private _resolveInitialLanguage;
192
266
  static ɵfac: i0.ɵɵFactoryDeclaration<RiviniaI18n<any>, never>;
@@ -194,6 +268,8 @@ export declare class RiviniaI18n<L extends string = string> {
194
268
  }
195
269
  /**
196
270
  * Configures `@rivinia/i18n` for the application. Call once at bootstrap.
271
+ * Also registers an app initializer that loads the initial language before
272
+ * first paint (opt out with `preload: false`).
197
273
  *
198
274
  * @example
199
275
  * ```ts
@@ -207,11 +283,36 @@ export declare class RiviniaI18n<L extends string = string> {
207
283
  * ```
208
284
  */
209
285
  export declare function provideRiviniaI18n<L extends string>(config: RiviniaI18nConfig<L>): EnvironmentProviders;
210
- /** Shorthand for `inject(RiviniaI18n)`. */
211
- export declare function injectRiviniaI18n(): RiviniaI18n<string>;
286
+ /** Shorthand for `inject(RiviniaI18n)` — preserves the configured language union. */
287
+ export declare function injectRiviniaI18n<L extends string = string>(): RiviniaI18n<L>;
288
+ /**
289
+ * Binds a config and its typed accessors together so `L` is inferred once
290
+ * from the configuration instead of being lost at the injection site.
291
+ *
292
+ * @example
293
+ * ```ts
294
+ * export const i18n = defineRiviniaI18n({
295
+ * defaultLanguage: 'ar',
296
+ * languages: [
297
+ * { id: 'ar', nativeName: 'العربية', dir: 'rtl' },
298
+ * { id: 'en', nativeName: 'English', dir: 'ltr' },
299
+ * ],
300
+ * });
301
+ * // app.config.ts
302
+ * providers: [i18n.provide()]
303
+ * // anywhere (typed 'ar' | 'en'):
304
+ * const lang = i18n.inject();
305
+ * ```
306
+ */
307
+ export declare function defineRiviniaI18n<L extends string>(config: RiviniaI18nConfig<L>): {
308
+ readonly config: RiviniaI18nConfig<L>;
309
+ provide: () => EnvironmentProviders;
310
+ inject: () => RiviniaI18n<L>;
311
+ };
212
312
  /** Progressive-enhancement wrapper around the View Transition API. */
213
313
  export declare class ViewTransitionService {
214
- private readonly _supported;
314
+ private readonly _doc;
315
+ private get _supported();
215
316
  run(callback: () => void): void;
216
317
  static ɵfac: i0.ɵɵFactoryDeclaration<ViewTransitionService, never>;
217
318
  static ɵprov: i0.ɵɵInjectableDeclaration<any>;