@rivinia/i18n 0.3.3 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,20 +1,20 @@
1
1
  import * as i0 from "@angular/core";
2
- import { DOCUMENT, InjectionToken, PendingTasks, Pipe, REQUEST, Service, TransferState, computed, effect, inject, makeEnvironmentProviders, makeStateKey, provideAppInitializer, signal } from "@angular/core";
2
+ import { DOCUMENT, InjectionToken, PendingTasks, Pipe, REQUEST, Service, TransferState, computed, effect, inject, isDevMode, makeEnvironmentProviders, makeStateKey, provideAppInitializer, signal } from "@angular/core";
3
3
  function jsonLoader(options) {
4
4
  return { async resolve() {
5
- const { JsonLoader } = await import("./rivinia-i18n-json-loader.impl-VXwAmyWL.mjs");
5
+ const { JsonLoader } = await import("./rivinia-i18n-json-loader.impl-Bq-W-UW9.mjs");
6
6
  return new JsonLoader(options);
7
7
  } };
8
8
  }
9
9
  function httpLoader(options) {
10
10
  return { async resolve() {
11
- const { HttpLoader } = await import("./rivinia-i18n-http-loader.impl-DVlKmSDL.mjs");
11
+ const { HttpLoader } = await import("./rivinia-i18n-http-loader.impl--BRii7w1.mjs");
12
12
  return new HttpLoader(options);
13
13
  } };
14
14
  }
15
15
  function remoteLoader(options) {
16
16
  return { async resolve() {
17
- const { RemoteLoader } = await import("./rivinia-i18n-remote-loader.impl-XKqdLHoJ.mjs");
17
+ const { RemoteLoader } = await import("./rivinia-i18n-remote-loader.impl-CqKS6JWN.mjs");
18
18
  return new RemoteLoader(options);
19
19
  } };
20
20
  }
@@ -103,13 +103,13 @@ function shouldSecureCookie(location) {
103
103
  function formatIcu(template, params, locale) {
104
104
  return parseMessage(template, 0, template.length, params, locale, null).text;
105
105
  }
106
- function parseMessage(src, start, end, params, locale, pluralValue) {
106
+ function parseMessage(src, start, end, params, locale, plural) {
107
107
  let out = "";
108
108
  let i = start;
109
109
  while (i < end) {
110
110
  const ch = src[i];
111
111
  if (ch === "{") {
112
- const arg = parseArgument(src, i, end, params, locale, pluralValue);
112
+ const arg = parseArgument(src, i, end, params, locale, plural);
113
113
  if (!arg.ok) return {
114
114
  text: out + src.slice(i, end),
115
115
  next: end,
@@ -122,8 +122,8 @@ function parseMessage(src, start, end, params, locale, pluralValue) {
122
122
  next: i,
123
123
  ok: true
124
124
  };
125
- else if (ch === "#" && pluralValue !== null) {
126
- out += String(pluralValue);
125
+ else if (ch === "#" && plural !== null) {
126
+ out += formatNumberValue(plural.value - plural.offset, locale, void 0) ?? "#";
127
127
  i++;
128
128
  } else {
129
129
  out += ch;
@@ -161,19 +161,18 @@ function parseArgument(src, start, end, params, locale, outerPlural) {
161
161
  i = skipSpaces(src, i + 1, end);
162
162
  const type = readWord(src, i, end);
163
163
  i = skipSpaces(src, type.next, end);
164
+ if (type.word === "number" || type.word === "date") return formatTypedArgument(src, start, i, end, type.word, params[name.word], locale) ?? rawSegment(src, start, end);
164
165
  if (i >= end || src[i] !== ",") return {
165
166
  text: src.slice(start, end),
166
167
  next: end,
167
168
  ok: true
168
169
  };
169
- if (type.word !== "plural" && type.word !== "select") return {
170
- text: src.slice(start, end),
171
- next: end,
172
- ok: true
173
- };
170
+ if (type.word !== "plural" && type.word !== "selectordinal" && type.word !== "select") return rawSegment(src, start, end);
174
171
  i++;
175
- const numeric = type.word === "plural" ? toFiniteNumber(params[name.word]) : null;
172
+ const numeric = type.word === "select" ? null : toFiniteNumber(params[name.word]);
173
+ const ordinal = type.word === "selectordinal";
176
174
  const branches = /* @__PURE__ */ new Map();
175
+ let offset = 0;
177
176
  i = skipSpaces(src, i, end);
178
177
  let closed = false;
179
178
  while (i < end) {
@@ -182,19 +181,23 @@ function parseArgument(src, start, end, params, locale, outerPlural) {
182
181
  closed = true;
183
182
  break;
184
183
  }
184
+ if (type.word !== "select") {
185
+ const offsetClause = readOffset(src, i, end);
186
+ if (offsetClause) {
187
+ offset = offsetClause.value;
188
+ i = offsetClause.next;
189
+ continue;
190
+ }
191
+ }
185
192
  const sel = readSelector(src, i, end);
186
- if (sel.selector === null) return {
187
- text: src.slice(start, end),
188
- next: end,
189
- ok: true
190
- };
193
+ if (sel.selector === null) return rawSegment(src, start, end);
191
194
  i = skipSpaces(src, sel.next, end);
192
- if (i >= end || src[i] !== "{") return {
193
- text: src.slice(start, end),
194
- next: end,
195
- ok: true
196
- };
197
- const body = parseMessage(src, i + 1, end, params, locale, numeric ?? outerPlural);
195
+ if (i >= end || src[i] !== "{") return rawSegment(src, start, end);
196
+ const scope = numeric !== null ? {
197
+ value: numeric,
198
+ offset
199
+ } : outerPlural;
200
+ const body = parseMessage(src, i + 1, end, params, locale, scope);
198
201
  branches.set(sel.selector, body.text);
199
202
  i = body.next + 1;
200
203
  }
@@ -225,7 +228,7 @@ function parseArgument(src, start, end, params, locale, outerPlural) {
225
228
  };
226
229
  let category;
227
230
  try {
228
- category = new Intl.PluralRules(locale).select(numeric);
231
+ category = pluralRules(locale, ordinal).select(numeric - offset);
229
232
  } catch {
230
233
  category = "other";
231
234
  }
@@ -235,6 +238,38 @@ function parseArgument(src, start, end, params, locale, outerPlural) {
235
238
  ok: true
236
239
  };
237
240
  }
241
+ function formatTypedArgument(src, start, i, end, kind, value, locale) {
242
+ let style;
243
+ if (i < end && src[i] === "}") style = void 0;
244
+ else if (i < end && src[i] === ",") {
245
+ const word = readWord(src, i + 1, end);
246
+ const after = skipSpaces(src, word.next, end);
247
+ if (after >= end || src[after] !== "}") return null;
248
+ style = word.word;
249
+ i = after;
250
+ } else return null;
251
+ const text = kind === "number" ? formatNumberValue(value, locale, style) : formatDateValue(value, locale, style);
252
+ if (text === null) return null;
253
+ return {
254
+ text,
255
+ next: i + 1,
256
+ ok: true
257
+ };
258
+ }
259
+ function readOffset(src, i, end) {
260
+ const start = skipSpaces(src, i, end);
261
+ if (!src.startsWith("offset:", start)) return null;
262
+ let j = start + 7;
263
+ const digits = j;
264
+ while (j < end && /[0-9]/.test(src[j])) j++;
265
+ if (j === digits) return null;
266
+ const value = Number(src.slice(digits, j));
267
+ if (!Number.isFinite(value)) return null;
268
+ return {
269
+ value,
270
+ next: j
271
+ };
272
+ }
238
273
  function toFiniteNumber(value) {
239
274
  if (typeof value === "number") return Number.isFinite(value) ? value : null;
240
275
  if (typeof value === "string" && value.trim() !== "") {
@@ -286,7 +321,153 @@ function readSelector(src, i, end) {
286
321
  next: word.next
287
322
  };
288
323
  }
324
+ function rawSegment(src, start, end) {
325
+ let depth = 0;
326
+ let i = start;
327
+ while (i < end) {
328
+ const ch = src[i];
329
+ if (ch === "{") depth++;
330
+ else if (ch === "}") {
331
+ depth--;
332
+ if (depth === 0) return {
333
+ text: src.slice(start, i + 1),
334
+ next: i + 1,
335
+ ok: true
336
+ };
337
+ }
338
+ i++;
339
+ }
340
+ return {
341
+ text: src.slice(start, end),
342
+ next: end,
343
+ ok: true
344
+ };
345
+ }
346
+ const CACHE_LIMIT = 40;
347
+ const numberFormats = /* @__PURE__ */ new Map();
348
+ const dateFormats = /* @__PURE__ */ new Map();
349
+ const pluralRulesByLocale = /* @__PURE__ */ new Map();
350
+ function memo(map, key, create) {
351
+ const hit = map.get(key);
352
+ if (hit !== void 0) return hit;
353
+ const created = create();
354
+ if (map.size >= CACHE_LIMIT) map.clear();
355
+ map.set(key, created);
356
+ return created;
357
+ }
358
+ function pluralRules(locale, ordinal) {
359
+ const key = `${ordinal ? "o" : "c"}|${locale}`;
360
+ return memo(pluralRulesByLocale, key, () => new Intl.PluralRules(locale, ordinal ? { type: "ordinal" } : void 0));
361
+ }
362
+ function formatNumberValue(value, locale, style) {
363
+ if (typeof value !== "number" || !Number.isFinite(value)) return null;
364
+ const options = numberOptions(style);
365
+ if (options === null) return null;
366
+ try {
367
+ const key = `${locale}|${JSON.stringify(options)}`;
368
+ return memo(numberFormats, key, () => new Intl.NumberFormat(locale, options)).format(value);
369
+ } catch {
370
+ return null;
371
+ }
372
+ }
373
+ function numberOptions(style) {
374
+ if (style === void 0) return {};
375
+ if (style === "percent") return { style: "percent" };
376
+ if (style === "integer") return { maximumFractionDigits: 0 };
377
+ if (style.startsWith("::currency/")) {
378
+ const code = style.slice(11);
379
+ if (/^[A-Za-z]{3}$/.test(code)) return {
380
+ style: "currency",
381
+ currency: code.toUpperCase()
382
+ };
383
+ }
384
+ return null;
385
+ }
386
+ const DATE_STYLES = /* @__PURE__ */ new Set([
387
+ "short",
388
+ "medium",
389
+ "long",
390
+ "full"
391
+ ]);
392
+ function formatDateValue(value, locale, style) {
393
+ const date = toDate(value);
394
+ if (date === null) return null;
395
+ if (style !== void 0 && !DATE_STYLES.has(style)) return null;
396
+ const options = style === void 0 ? {} : { dateStyle: style };
397
+ try {
398
+ const key = `${locale}|${style ?? ""}`;
399
+ return memo(dateFormats, key, () => new Intl.DateTimeFormat(locale, options)).format(date);
400
+ } catch {
401
+ return null;
402
+ }
403
+ }
404
+ function toDate(value) {
405
+ if (typeof value === "number") {
406
+ if (!Number.isFinite(value)) return null;
407
+ const date = new Date(value);
408
+ return Number.isNaN(date.getTime()) ? null : date;
409
+ }
410
+ if (Object.prototype.toString.call(value) === "[object Date]") {
411
+ const date = value;
412
+ return Number.isNaN(date.getTime()) ? null : date;
413
+ }
414
+ return null;
415
+ }
289
416
  const RIVINIA_I18N_CONFIG = new InjectionToken("RIVINIA_I18N_CONFIG");
417
+ function createLoaderContext(request, doc) {
418
+ const documentBase = readBaseUri(doc);
419
+ if (!request) return {
420
+ baseUrl: documentBase,
421
+ isServer: false
422
+ };
423
+ const requestUrl = parseUrl(request.url);
424
+ const baseHref = readBaseHref(doc);
425
+ if (baseHref) {
426
+ const resolved = resolveUrl(baseHref, requestUrl?.href ?? documentBase);
427
+ if (resolved) return {
428
+ baseUrl: resolved,
429
+ isServer: true
430
+ };
431
+ }
432
+ if (requestUrl) return {
433
+ baseUrl: `${requestUrl.origin}/`,
434
+ isServer: true
435
+ };
436
+ return {
437
+ baseUrl: documentBase,
438
+ isServer: true
439
+ };
440
+ }
441
+ function readBaseUri(doc) {
442
+ try {
443
+ const uri = doc?.baseURI;
444
+ if (typeof uri === "string" && uri.length > 0) return uri;
445
+ } catch {}
446
+ return "/";
447
+ }
448
+ function readBaseHref(doc) {
449
+ try {
450
+ const href = (doc.querySelector?.("base[href]"))?.getAttribute("href")?.trim();
451
+ return href ? href : null;
452
+ } catch {
453
+ return null;
454
+ }
455
+ }
456
+ function parseUrl(value) {
457
+ if (!value) return null;
458
+ try {
459
+ return new URL(value);
460
+ } catch {
461
+ return null;
462
+ }
463
+ }
464
+ function resolveUrl(value, base) {
465
+ try {
466
+ return new URL(value, base).href;
467
+ } catch {
468
+ return null;
469
+ }
470
+ }
290
471
  var ViewTransitionService = class ViewTransitionService {
291
472
  _doc = inject(DOCUMENT);
292
473
  run(callback) {
@@ -296,7 +477,7 @@ var ViewTransitionService = class ViewTransitionService {
296
477
  }
297
478
  static ɵfac = i0.ɵɵngDeclareFactory({
298
479
  minVersion: "12.0.0",
299
- version: "22.2.2",
480
+ version: "22.2.3",
300
481
  ngImport: i0,
301
482
  type: ViewTransitionService,
302
483
  deps: [],
@@ -304,14 +485,14 @@ var ViewTransitionService = class ViewTransitionService {
304
485
  });
305
486
  static ɵprov = i0.ɵɵngDeclareService({
306
487
  minVersion: "22.0.0",
307
- version: "22.2.2",
488
+ version: "22.2.3",
308
489
  ngImport: i0,
309
490
  type: ViewTransitionService
310
491
  });
311
492
  };
312
493
  i0.ɵɵngDeclareClassMetadata({
313
494
  minVersion: "12.0.0",
314
- version: "22.2.2",
495
+ version: "22.2.3",
315
496
  ngImport: i0,
316
497
  type: ViewTransitionService,
317
498
  decorators: [{ type: Service }]
@@ -322,15 +503,19 @@ var RiviniaI18n = class RiviniaI18n {
322
503
  _storageKey = this._config.storageKey ?? "rivinia.i18n.language";
323
504
  _storageStrategy = this._config.storageStrategy ?? "local";
324
505
  _autoApplyDirection = this._config.autoApplyDirection ?? true;
506
+ _fallbackId = this._config.fallbackLanguage ?? null;
325
507
  _doc = inject(DOCUMENT);
326
508
  _request = inject(REQUEST, { optional: true });
327
509
  _transfer = inject(TransferState, { optional: true });
510
+ loaderContext = createLoaderContext(this._request ?? null, this._doc);
328
511
  _currentLanguageId = signal(this._resolveInitialLanguage(), ...ngDevMode ? [{ debugName: "_currentLanguageId" }] : /* istanbul ignore next */ []);
329
512
  _languages = signal(this._config.languages, ...ngDevMode ? [{ debugName: "_languages" }] : /* istanbul ignore next */ []);
330
513
  _loadedTranslations = signal({}, ...ngDevMode ? [{ debugName: "_loadedTranslations" }] : /* istanbul ignore next */ []);
331
- _getLoader = this._config.loader?.resolve ?? (() => jsonLoader().resolve());
514
+ _fallbackDict = signal(null, ...ngDevMode ? [{ debugName: "_fallbackDict" }] : /* istanbul ignore next */ []);
515
+ _getLoader = (context) => this._config.loader ? this._config.loader.resolve(context) : jsonLoader().resolve(context);
332
516
  _resolvedLoader = null;
333
517
  _translationsCache = /* @__PURE__ */ new Map();
518
+ _generations = /* @__PURE__ */ new Map();
334
519
  _inflight = /* @__PURE__ */ new Map();
335
520
  _applyCount = 0;
336
521
  _initialized = false;
@@ -351,9 +536,21 @@ var RiviniaI18n = class RiviniaI18n {
351
536
  isLoading = computed(() => this._loadingState() === "loading", ...ngDevMode ? [{ debugName: "isLoading" }] : /* istanbul ignore next */ []);
352
537
  _ready = signal(false, ...ngDevMode ? [{ debugName: "_ready" }] : /* istanbul ignore next */ []);
353
538
  ready = this._ready.asReadonly();
539
+ _warnOnMissingKey = this._config.warnOnMissingKey ?? (isDevMode() && this._config.onMissingKey === void 0);
540
+ _missingKeys = signal([], ...ngDevMode ? [{ debugName: "_missingKeys" }] : /* istanbul ignore next */ []);
541
+ _reportedMissingKeys = /* @__PURE__ */ new Set();
542
+ _pendingMissingKeys = [];
543
+ _missingFlushQueued = false;
544
+ missingKeys = this._missingKeys.asReadonly();
545
+ clearMissingKeys() {
546
+ this._reportedMissingKeys.clear();
547
+ this._pendingMissingKeys.length = 0;
548
+ this._missingKeys.set([]);
549
+ }
354
550
  constructor() {
355
551
  if (this._config.languages.length === 0) throw new Error("[rivinia/i18n] At least one language must be provided in the languages array.");
356
552
  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.`);
553
+ if (this._fallbackId !== null && !this._config.languages.some((l) => l.id === this._fallbackId)) throw new Error(`[rivinia/i18n] fallbackLanguage "${this._fallbackId}" must be one of the configured language IDs.`);
357
554
  effect(() => {
358
555
  const id = this._currentLanguageId();
359
556
  this._writeStored(id);
@@ -375,6 +572,9 @@ var RiviniaI18n = class RiviniaI18n {
375
572
  const done = this._tasks?.add();
376
573
  try {
377
574
  const current = this._currentLanguageId();
575
+ const fallback = this._fallbackId;
576
+ const hasFallback = fallback !== null && fallback !== current;
577
+ const preload = this._config.preload ?? true;
378
578
  const transferred = this.readTransfer(current);
379
579
  if (transferred) {
380
580
  this._translationsCache.set(current, transferred);
@@ -382,8 +582,22 @@ var RiviniaI18n = class RiviniaI18n {
382
582
  } else {
383
583
  const inline = this._config.translations?.[current];
384
584
  if (inline) this._loadedTranslations.set(inline);
385
- if (this._config.preload ?? true) await this._loadTranslations(current);
386
585
  }
586
+ let fallbackTransferred = null;
587
+ if (hasFallback) {
588
+ fallbackTransferred = this.readTransfer(fallback);
589
+ if (fallbackTransferred) {
590
+ this._translationsCache.set(fallback, fallbackTransferred);
591
+ this._fallbackDict.set(fallbackTransferred);
592
+ }
593
+ }
594
+ const loads = [];
595
+ if (!transferred && preload) loads.push(this._loadTranslations(current));
596
+ if (hasFallback && !fallbackTransferred && preload) loads.push(this._loadTranslations(fallback, {
597
+ silent: true,
598
+ background: true
599
+ }));
600
+ await Promise.all(loads);
387
601
  } finally {
388
602
  this._ready.set(true);
389
603
  done?.();
@@ -392,18 +606,57 @@ var RiviniaI18n = class RiviniaI18n {
392
606
  translate(keyOrTranslations, defaultValueOrParams, maybeParams) {
393
607
  if (typeof keyOrTranslations === "string") {
394
608
  const { defaultValue, params } = normalizeKeyArgs(defaultValueOrParams, maybeParams);
395
- const loaded = this._loadedTranslations();
396
- const resolved = this._resolveKey(loaded, keyOrTranslations);
397
- if (resolved !== void 0) return this.render(resolved, params);
398
- const fallback = defaultValue ?? keyOrTranslations;
399
- return params ? this.render(fallback, params) : fallback;
609
+ return this._resolveKeyText(keyOrTranslations, defaultValue, params);
400
610
  }
401
- return keyOrTranslations[this._currentLanguageId()] ?? Object.values(keyOrTranslations)[0] ?? "";
611
+ const currentId = this._currentLanguageId();
612
+ const fallbackId = this._fallbackId;
613
+ return keyOrTranslations[currentId] ?? (fallbackId !== null ? keyOrTranslations[fallbackId] : void 0) ?? Object.values(keyOrTranslations)[0] ?? "";
614
+ }
615
+ t(key, defaultValueOrParams, maybeParams) {
616
+ const defaultValue = typeof defaultValueOrParams === "string" ? defaultValueOrParams : void 0;
617
+ const paramsSource = typeof defaultValueOrParams === "string" ? maybeParams : defaultValueOrParams;
618
+ return computed(() => {
619
+ const params = typeof paramsSource === "function" ? paramsSource() : paramsSource;
620
+ return this._resolveKeyText(key, defaultValue, params);
621
+ });
622
+ }
623
+ _resolveKeyText(key, defaultValue, params) {
624
+ const resolved = this._lookupKey(key);
625
+ if (resolved !== void 0) return this.render(resolved.text, params, resolved.locale);
626
+ if (defaultValue === void 0) this._reportMissingKey(key);
627
+ const fallback = defaultValue ?? key;
628
+ return params ? this.render(fallback, params, this.locale()) : fallback;
402
629
  }
403
630
  loadedTranslations = this._loadedTranslations.asReadonly();
404
631
  async loadTranslations(languageId, opts) {
405
632
  return (await this._loadTranslations(languageId, opts)).data;
406
633
  }
634
+ reload(languageId) {
635
+ if (languageId !== void 0) {
636
+ if (!this._languages().some((l) => l.id === languageId)) return Promise.resolve(false);
637
+ this._invalidate(languageId);
638
+ return this._reloadOne(languageId);
639
+ }
640
+ const currentId = this._currentLanguageId();
641
+ const fallbackId = this._fallbackId;
642
+ for (const cachedId of [...this._translationsCache.keys()]) if (cachedId !== currentId && cachedId !== fallbackId) this._translationsCache.delete(cachedId);
643
+ for (const language of this._languages()) this._invalidate(language.id);
644
+ const currentLoad = this._reloadOne(currentId);
645
+ if (fallbackId !== null && fallbackId !== currentId) this._reloadOne(fallbackId);
646
+ return currentLoad;
647
+ }
648
+ _reloadOne(languageId) {
649
+ return this._loadTranslations(languageId, {
650
+ force: true,
651
+ background: languageId !== this._currentLanguageId()
652
+ }).then((result) => result.ok);
653
+ }
654
+ _generationOf(languageId) {
655
+ return this._generations.get(languageId) ?? 0;
656
+ }
657
+ _invalidate(languageId) {
658
+ this._generations.set(languageId, this._generationOf(languageId) + 1);
659
+ }
407
660
  toggle() {
408
661
  const langs = this._languages();
409
662
  if (langs.length < 2) return;
@@ -478,36 +731,112 @@ var RiviniaI18n = class RiviniaI18n {
478
731
  });
479
732
  this._viewTransition.run(apply);
480
733
  } else apply();
481
- if (!opts?.skipLoad) this._loadTranslations(id);
734
+ if (!opts?.skipLoad) {
735
+ this._loadTranslations(id);
736
+ this._ensureFallback();
737
+ }
482
738
  }
483
- render(template, params) {
739
+ render(template, params, locale) {
484
740
  if (!params) return template;
485
741
  if (!template.includes("{")) return template;
486
742
  try {
487
- return formatIcu(template, params, this.locale());
743
+ return formatIcu(template, params, locale);
488
744
  } catch {
489
745
  return template;
490
746
  }
491
747
  }
748
+ _lookupKey(key) {
749
+ const currentValue = this._resolveKey(this._loadedTranslations(), key);
750
+ if (currentValue !== void 0) return {
751
+ text: currentValue,
752
+ locale: this.locale()
753
+ };
754
+ const fallbackId = this._fallbackId;
755
+ if (fallbackId === null || fallbackId === this._currentLanguageId()) return void 0;
756
+ const fallbackDict = this._fallbackDict() ?? this._config.translations?.[fallbackId] ?? null;
757
+ if (!fallbackDict) return void 0;
758
+ const fallbackValue = this._resolveKey(fallbackDict, key);
759
+ if (fallbackValue === void 0) return void 0;
760
+ return {
761
+ text: fallbackValue,
762
+ locale: this._localeOf(fallbackId)
763
+ };
764
+ }
765
+ _localeOf(languageId) {
766
+ return this._languages().find((l) => l.id === languageId)?.locale ?? languageId;
767
+ }
768
+ _ensureFallback() {
769
+ const fallbackId = this._fallbackId;
770
+ if (fallbackId === null || fallbackId === this._currentLanguageId()) return;
771
+ if (this._hasDictionary(fallbackId)) return;
772
+ this._loadTranslations(fallbackId, {
773
+ silent: true,
774
+ background: true
775
+ });
776
+ }
777
+ _hasDictionary(languageId) {
778
+ return this._translationsCache.has(languageId) || this._config.translations?.[languageId] !== void 0;
779
+ }
780
+ _reportMissingKey(key) {
781
+ if (!this._hasDictionary(this._currentLanguageId())) return;
782
+ if (this._reportedMissingKeys.has(key)) return;
783
+ this._reportedMissingKeys.add(key);
784
+ const language = this._currentLanguageId();
785
+ const fallbackLanguage = this._fallbackId;
786
+ const event = fallbackLanguage === null ? {
787
+ key,
788
+ language
789
+ } : {
790
+ key,
791
+ language,
792
+ fallbackLanguage
793
+ };
794
+ this._pendingMissingKeys.push(key);
795
+ this._queueMissingFlush();
796
+ this._config.onMissingKey?.(event);
797
+ if (this._warnOnMissingKey) console.warn(`[rivinia/i18n] Missing key "${key}" for language "${language}"` + (fallbackLanguage === null ? "." : ` (fallback "${fallbackLanguage}" has no value either).`));
798
+ }
799
+ _queueMissingFlush() {
800
+ if (this._missingFlushQueued) return;
801
+ this._missingFlushQueued = true;
802
+ queueMicrotask(() => {
803
+ this._missingFlushQueued = false;
804
+ const pending = this._pendingMissingKeys.splice(0);
805
+ if (pending.length === 0) return;
806
+ this._missingKeys.update((current) => [...current, ...pending]);
807
+ });
808
+ }
492
809
  async _loadTranslations(languageId, opts) {
493
810
  const current = () => languageId === this._currentLanguageId();
494
- const cached = this._translationsCache.get(languageId);
495
- if (cached) {
496
- if (!opts?.silent && current()) this._loadedTranslations.set(cached);
497
- return {
498
- data: cached,
499
- ok: true
500
- };
811
+ const background = opts?.background === true;
812
+ if (!opts?.force) {
813
+ const cached = this._translationsCache.get(languageId);
814
+ if (cached) {
815
+ if (!opts?.silent && current()) this._loadedTranslations.set(cached);
816
+ if (languageId === this._fallbackId) this._fallbackDict.set(cached);
817
+ return {
818
+ data: cached,
819
+ ok: true
820
+ };
821
+ }
822
+ const inflight = this._inflight.get(languageId);
823
+ if (inflight) return inflight;
501
824
  }
502
- const inflight = this._inflight.get(languageId);
503
- if (inflight) return inflight;
504
- this._loadingState.set("loading");
505
- const task = (async () => {
825
+ if (!background) this._loadingState.set("loading");
826
+ const generation = this._generationOf(languageId);
827
+ let task;
828
+ task = (async () => {
829
+ const stale = () => this._generationOf(languageId) !== generation;
506
830
  try {
507
- if (!this._resolvedLoader) this._resolvedLoader = await this._getLoader();
508
- const translations = await this._resolvedLoader.load(languageId);
831
+ if (!this._resolvedLoader) this._resolvedLoader = await this._getLoader(this.loaderContext);
832
+ const translations = await this._resolvedLoader.load(languageId, this.loaderContext);
833
+ if (stale()) return {
834
+ data: {},
835
+ ok: false
836
+ };
509
837
  this._translationsCache.set(languageId, translations);
510
838
  this.writeTransfer(languageId, translations);
839
+ if (languageId === this._fallbackId && !current()) this._fallbackDict.set(translations);
511
840
  if (!opts?.silent && current()) {
512
841
  this._loadedTranslations.set(translations);
513
842
  this._loadingError.set(null);
@@ -518,7 +847,11 @@ var RiviniaI18n = class RiviniaI18n {
518
847
  ok: true
519
848
  };
520
849
  } catch (error) {
521
- if (current()) {
850
+ if (stale()) return {
851
+ data: {},
852
+ ok: false
853
+ };
854
+ if (!background && current()) {
522
855
  this._loadingError.set(error);
523
856
  this._loadingState.set("error");
524
857
  }
@@ -528,8 +861,10 @@ var RiviniaI18n = class RiviniaI18n {
528
861
  ok: false
529
862
  };
530
863
  } finally {
531
- this._inflight.delete(languageId);
532
- if (this._inflight.size === 0 && this._loadingState() === "loading") this._loadingState.set("idle");
864
+ if (this._inflight.get(languageId) === task) {
865
+ this._inflight.delete(languageId);
866
+ if (!background && this._inflight.size === 0 && this._loadingState() === "loading") this._loadingState.set("idle");
867
+ }
533
868
  }
534
869
  })();
535
870
  this._inflight.set(languageId, task);
@@ -590,7 +925,7 @@ var RiviniaI18n = class RiviniaI18n {
590
925
  }
591
926
  static ɵfac = i0.ɵɵngDeclareFactory({
592
927
  minVersion: "12.0.0",
593
- version: "22.2.2",
928
+ version: "22.2.3",
594
929
  ngImport: i0,
595
930
  type: RiviniaI18n,
596
931
  deps: [],
@@ -598,14 +933,14 @@ var RiviniaI18n = class RiviniaI18n {
598
933
  });
599
934
  static ɵprov = i0.ɵɵngDeclareService({
600
935
  minVersion: "22.0.0",
601
- version: "22.2.2",
936
+ version: "22.2.3",
602
937
  ngImport: i0,
603
938
  type: RiviniaI18n
604
939
  });
605
940
  };
606
941
  i0.ɵɵngDeclareClassMetadata({
607
942
  minVersion: "12.0.0",
608
- version: "22.2.2",
943
+ version: "22.2.3",
609
944
  ngImport: i0,
610
945
  type: RiviniaI18n,
611
946
  decorators: [{ type: Service }],
@@ -643,7 +978,7 @@ var RTranslatePipe = class RTranslatePipe {
643
978
  }
644
979
  static ɵfac = i0.ɵɵngDeclareFactory({
645
980
  minVersion: "12.0.0",
646
- version: "22.2.2",
981
+ version: "22.2.3",
647
982
  ngImport: i0,
648
983
  type: RTranslatePipe,
649
984
  deps: [],
@@ -651,7 +986,7 @@ var RTranslatePipe = class RTranslatePipe {
651
986
  });
652
987
  static ɵpipe = i0.ɵɵngDeclarePipe({
653
988
  minVersion: "14.0.0",
654
- version: "22.2.2",
989
+ version: "22.2.3",
655
990
  ngImport: i0,
656
991
  type: RTranslatePipe,
657
992
  isStandalone: true,
@@ -661,7 +996,7 @@ var RTranslatePipe = class RTranslatePipe {
661
996
  };
662
997
  i0.ɵɵngDeclareClassMetadata({
663
998
  minVersion: "12.0.0",
664
- version: "22.2.2",
999
+ version: "22.2.3",
665
1000
  ngImport: i0,
666
1001
  type: RTranslatePipe,
667
1002
  decorators: [{