@sixbell-telco/sdk 4.6.1 → 4.8.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/CHANGELOG.md +43 -0
- package/fesm2022/sixbell-telco-sdk-layouts.mjs +32 -2
- package/fesm2022/sixbell-telco-sdk-layouts.mjs.map +1 -1
- package/fesm2022/sixbell-telco-sdk-utils-mfe.mjs +5 -14
- package/fesm2022/sixbell-telco-sdk-utils-mfe.mjs.map +1 -1
- package/fesm2022/sixbell-telco-sdk-utils-runtime-config.mjs +15 -3
- package/fesm2022/sixbell-telco-sdk-utils-runtime-config.mjs.map +1 -1
- package/fesm2022/sixbell-telco-sdk-utils-translation-testing.mjs +5 -1
- package/fesm2022/sixbell-telco-sdk-utils-translation-testing.mjs.map +1 -1
- package/fesm2022/sixbell-telco-sdk-utils-translation.mjs +358 -129
- package/fesm2022/sixbell-telco-sdk-utils-translation.mjs.map +1 -1
- package/layouts/README.md +7 -2
- package/layouts/src/page-banner/page-banner.component.d.ts +10 -0
- package/manifest.json +1 -1
- package/package.json +1 -1
- package/src/_index.css +29 -7
- package/utils/mfe/README.md +1 -1
- package/utils/mfe/src/provide-mfe-shadow-shell.d.ts +5 -1
- package/utils/runtime-config/src/http-client.d.ts +7 -0
- package/utils/translation/README.md +9 -5
- package/utils/translation/src/title-strategy/translated-title-strategy.d.ts +9 -0
- package/utils/translation/src/translation.service.d.ts +81 -6
- package/utils/translation/testing/src/translation-testing.d.ts +2 -0
|
@@ -3,7 +3,7 @@ import { inject, RendererFactory2, Injectable, DestroyRef, signal, computed, Inj
|
|
|
3
3
|
import { TranslateService, provideTranslateService, provideMissingTranslationHandler, provideTranslateLoader } from '@ngx-translate/core';
|
|
4
4
|
export * from '@ngx-translate/core';
|
|
5
5
|
import { LoggerService } from '@sixbell-telco/sdk/utils/logger';
|
|
6
|
-
import { RuntimeHttpClient, RuntimeConfigStore, RuntimeConfigLoader, RuntimeUpdateAdapter } from '@sixbell-telco/sdk/utils/runtime-config';
|
|
6
|
+
import { RuntimeHttpClient, RuntimeHttpError, RuntimeConfigStore, RuntimeConfigLoader, RuntimeUpdateAdapter } from '@sixbell-telco/sdk/utils/runtime-config';
|
|
7
7
|
import { firstValueFrom, from } from 'rxjs';
|
|
8
8
|
import { DOCUMENT } from '@angular/common';
|
|
9
9
|
import { Title } from '@angular/platform-browser';
|
|
@@ -259,6 +259,12 @@ function createLanguage(config) {
|
|
|
259
259
|
name: config.name,
|
|
260
260
|
};
|
|
261
261
|
}
|
|
262
|
+
/** How many times a language load restarts when the translation paths change while it fetches. */
|
|
263
|
+
const MAX_PATH_CHANGE_RESTARTS = 3;
|
|
264
|
+
function normalizeTranslationPath(path) {
|
|
265
|
+
const trimmed = path.trim();
|
|
266
|
+
return trimmed.endsWith('/') ? trimmed : `${trimmed}/`;
|
|
267
|
+
}
|
|
262
268
|
function extendDefaultLanguages(additionalLanguages) {
|
|
263
269
|
return [...DEFAULT_LANGUAGES, ...additionalLanguages];
|
|
264
270
|
}
|
|
@@ -278,14 +284,28 @@ class TranslationService {
|
|
|
278
284
|
translationHttpClient = null;
|
|
279
285
|
hasAppliedInitialLanguage = false;
|
|
280
286
|
isUsingFallbackConfig = false;
|
|
281
|
-
prefetchLanguages = true;
|
|
282
287
|
isApplyingRuntimeConfig = false;
|
|
283
288
|
bundleRefreshId = 0;
|
|
284
289
|
inactiveRefreshIds = new Map();
|
|
290
|
+
/** The last config passed to `configure()`, before the paths added with `addTranslationPaths()`. */
|
|
291
|
+
baseConfig = null;
|
|
292
|
+
/** Paths added at runtime (e.g. a federated remote's i18n folder); every applied config keeps them. */
|
|
293
|
+
addedPaths = [];
|
|
294
|
+
/** Bumped whenever the translation paths change, so a load started with older paths fetches again. */
|
|
295
|
+
pathsEpoch = 0;
|
|
296
|
+
/** Languages this service loaded, set or asked ngx-translate to load: the ones a refresh must update. */
|
|
297
|
+
knownLanguages = new Set();
|
|
298
|
+
/** Languages whose last load had a file that could not be read; they are fetched again on next use. */
|
|
299
|
+
incompleteLanguages = new Set();
|
|
300
|
+
/** The latest runtime refresh, so `addTranslationPaths()` resolves only when its paths are applied. */
|
|
301
|
+
latestRefresh = Promise.resolve();
|
|
302
|
+
/** The first `setRuntimeConfig()` while it runs, so paths added meanwhile can wait for it. */
|
|
303
|
+
firstLoad = null;
|
|
304
|
+
/** Bundles the SDK loader read in full (every file answered, paths unchanged): they replace a language. */
|
|
305
|
+
completeBundles = new WeakSet();
|
|
285
306
|
runtimeHash = null;
|
|
286
307
|
runtimeLoader;
|
|
287
308
|
runtimeMeta;
|
|
288
|
-
pendingUpdatedLanguages = new Set();
|
|
289
309
|
bootstrapValidated = false;
|
|
290
310
|
translationTick = signal(0);
|
|
291
311
|
localeConfig = signal({
|
|
@@ -326,18 +346,6 @@ class TranslationService {
|
|
|
326
346
|
availableLanguages = availableLanguages.filter((lang) => !config.excludeLanguages?.includes(lang.code));
|
|
327
347
|
}
|
|
328
348
|
const defaultLang = config.defaultLang || DEFAULT_LANGUAGE_CODE;
|
|
329
|
-
const newPaths = (config.translationPaths || DEFAULT_TRANSLATION_PATHS);
|
|
330
|
-
if (JSON.stringify(newPaths) !== JSON.stringify(this.currentTranslationPaths)) {
|
|
331
|
-
this.currentTranslationPaths = newPaths;
|
|
332
|
-
this.logger.debug('Translation paths updated', {
|
|
333
|
-
component: 'TranslationService',
|
|
334
|
-
action: 'configure',
|
|
335
|
-
newPaths,
|
|
336
|
-
});
|
|
337
|
-
if (!this.isApplyingRuntimeConfig) {
|
|
338
|
-
this.reloadForNewPaths(this.getCurrentLanguage());
|
|
339
|
-
}
|
|
340
|
-
}
|
|
341
349
|
this.config = {
|
|
342
350
|
availableLanguages,
|
|
343
351
|
defaultLanguage: defaultLang,
|
|
@@ -359,6 +367,11 @@ class TranslationService {
|
|
|
359
367
|
availableLangCodes: availableCodes,
|
|
360
368
|
});
|
|
361
369
|
this.resolveStoredLanguage();
|
|
370
|
+
// After the new languages are set, so a refresh plans with this config, not the previous one.
|
|
371
|
+
this.baseConfig = config;
|
|
372
|
+
if (this.updatePaths(this.withAddedPaths(config.translationPaths)) && !this.isApplyingRuntimeConfig) {
|
|
373
|
+
this.reloadForNewPaths(this.getCurrentLanguage());
|
|
374
|
+
}
|
|
362
375
|
if (this.initialized) {
|
|
363
376
|
// This is a runtime config update (not initial construction)
|
|
364
377
|
// Keep current language resolved from storage unless we're doing a fresh init
|
|
@@ -389,21 +402,85 @@ class TranslationService {
|
|
|
389
402
|
}
|
|
390
403
|
this.currentLanguage.set(this.config.defaultLanguage);
|
|
391
404
|
}
|
|
405
|
+
/** The config's paths (or the defaults) followed by the runtime-added paths it does not list. */
|
|
406
|
+
withAddedPaths(paths) {
|
|
407
|
+
const base = [...(paths || DEFAULT_TRANSLATION_PATHS)];
|
|
408
|
+
const listed = new Set(base.map(normalizeTranslationPath));
|
|
409
|
+
return [...base, ...this.addedPaths.filter((path) => !listed.has(path))];
|
|
410
|
+
}
|
|
411
|
+
/** Sets the translation paths; returns `true` when they changed. */
|
|
412
|
+
updatePaths(paths) {
|
|
413
|
+
if (JSON.stringify(paths) === JSON.stringify(this.currentTranslationPaths)) {
|
|
414
|
+
return false;
|
|
415
|
+
}
|
|
416
|
+
this.currentTranslationPaths = paths;
|
|
417
|
+
this.pathsEpoch += 1;
|
|
418
|
+
this.logger.debug('Translation paths updated', {
|
|
419
|
+
component: 'TranslationService',
|
|
420
|
+
action: 'configure',
|
|
421
|
+
newPaths: paths,
|
|
422
|
+
});
|
|
423
|
+
return true;
|
|
424
|
+
}
|
|
392
425
|
reloadForNewPaths(targetLang) {
|
|
393
426
|
if (this.ready()) {
|
|
394
|
-
|
|
427
|
+
this.trackRefresh(this.refreshLoadedBundles());
|
|
395
428
|
return;
|
|
396
429
|
}
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
430
|
+
this.knownLanguages.add(targetLang);
|
|
431
|
+
this.translate.reloadLang(targetLang);
|
|
432
|
+
}
|
|
433
|
+
/**
|
|
434
|
+
* Adds translation folders at runtime, e.g. a federated remote's `/<mount>/assets/i18n/` when its
|
|
435
|
+
* routes load. The paths stay in every config applied afterwards (runtime refreshes included), and
|
|
436
|
+
* every language already loaded is fetched again with them: the active language and the loaded
|
|
437
|
+
* fallback before this resolves, the others in the background. Languages never loaded keep loading
|
|
438
|
+
* lazily, with all the paths, on first use. Calling it again with paths already added fetches the
|
|
439
|
+
* languages whose last load had a file that could not be read, so a remote that failed is retried.
|
|
440
|
+
*/
|
|
441
|
+
async addTranslationPaths(paths) {
|
|
442
|
+
const added = Array.from(new Set(paths.map(normalizeTranslationPath).filter((path) => path !== '/'))).filter((path) => !this.addedPaths.includes(path) && !this.currentTranslationPaths.map(normalizeTranslationPath).includes(path));
|
|
443
|
+
if (!added.length) {
|
|
444
|
+
await this.retryIncompleteLanguages();
|
|
445
|
+
await this.settleRefreshes();
|
|
446
|
+
return;
|
|
447
|
+
}
|
|
448
|
+
this.addedPaths.push(...added);
|
|
449
|
+
if (!this.baseConfig) {
|
|
450
|
+
// No config applied yet: the first `setRuntimeConfig()` picks the paths up.
|
|
451
|
+
return;
|
|
452
|
+
}
|
|
453
|
+
if (!this.ready()) {
|
|
454
|
+
// First load in flight: loads still fetching restart with the new paths (`loadLanguageBundle`), and
|
|
455
|
+
// the first load fetches again the languages it already finished (`loadFirstConfig`).
|
|
456
|
+
if (this.updatePaths(this.withAddedPaths(this.baseConfig.translationPaths)) && !this.isApplyingRuntimeConfig) {
|
|
457
|
+
this.reloadForNewPaths(this.currentLanguage());
|
|
458
|
+
}
|
|
459
|
+
if (this.firstLoad) {
|
|
460
|
+
await this.firstLoad.catch(() => undefined);
|
|
461
|
+
}
|
|
462
|
+
await this.settleRefreshes();
|
|
463
|
+
return;
|
|
464
|
+
}
|
|
465
|
+
await this.setRuntimeConfig(this.baseConfig);
|
|
466
|
+
await this.settleRefreshes();
|
|
467
|
+
}
|
|
468
|
+
trackRefresh(refresh) {
|
|
469
|
+
this.latestRefresh = refresh;
|
|
470
|
+
return refresh;
|
|
471
|
+
}
|
|
472
|
+
/** Waits until no newer refresh superseded the one being awaited. */
|
|
473
|
+
async settleRefreshes() {
|
|
474
|
+
let current;
|
|
475
|
+
do {
|
|
476
|
+
current = this.latestRefresh;
|
|
477
|
+
await current.catch(() => undefined);
|
|
478
|
+
} while (current !== this.latestRefresh);
|
|
479
|
+
}
|
|
480
|
+
async retryIncompleteLanguages() {
|
|
481
|
+
const loaded = this.loadedLanguages();
|
|
482
|
+
const languages = [...this.incompleteLanguages].filter((lang) => loaded.has(lang));
|
|
483
|
+
await Promise.all(languages.map((lang) => this.refreshLanguageInBackground(lang)));
|
|
407
484
|
}
|
|
408
485
|
/**
|
|
409
486
|
* Applies a runtime config. On the first load `ready()` stays false until the bundle is in. Once
|
|
@@ -412,9 +489,21 @@ class TranslationService {
|
|
|
412
489
|
*/
|
|
413
490
|
async setRuntimeConfig(config) {
|
|
414
491
|
if (this.ready()) {
|
|
415
|
-
await this.refreshRuntimeConfig(config);
|
|
492
|
+
await this.trackRefresh(this.refreshRuntimeConfig(config));
|
|
416
493
|
return;
|
|
417
494
|
}
|
|
495
|
+
const firstLoad = this.loadFirstConfig(config);
|
|
496
|
+
this.firstLoad = firstLoad;
|
|
497
|
+
try {
|
|
498
|
+
await firstLoad;
|
|
499
|
+
}
|
|
500
|
+
finally {
|
|
501
|
+
if (this.firstLoad === firstLoad) {
|
|
502
|
+
this.firstLoad = null;
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
async loadFirstConfig(config) {
|
|
418
507
|
this.ready.set(false);
|
|
419
508
|
this.logger.debug('setRuntimeConfig - starting', {
|
|
420
509
|
component: 'TranslationService',
|
|
@@ -423,17 +512,26 @@ class TranslationService {
|
|
|
423
512
|
});
|
|
424
513
|
// Update configuration (this will update currentLanguage signal and restore from storage)
|
|
425
514
|
this.isApplyingRuntimeConfig = true;
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
this.
|
|
515
|
+
try {
|
|
516
|
+
this.configure(config);
|
|
517
|
+
// Apply language now that runtime config has loaded
|
|
518
|
+
// This saves to storage with the correct default from config file
|
|
519
|
+
const targetLang = this.currentLanguage();
|
|
520
|
+
const epoch = this.pathsEpoch;
|
|
521
|
+
this.knownLanguages.add(targetLang);
|
|
522
|
+
await firstValueFrom(this.translate.reloadLang(targetLang));
|
|
523
|
+
this.applyLanguage();
|
|
524
|
+
await this.waitForFallbackLanguage();
|
|
525
|
+
if (epoch !== this.pathsEpoch) {
|
|
526
|
+
// Paths were added while loading (`addTranslationPaths()` during boot): a language that finished
|
|
527
|
+
// with the old paths gets the new ones before the first load resolves.
|
|
528
|
+
await this.refreshLoadedBundles();
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
finally {
|
|
532
|
+
// Also when a custom loader rejects: later configs must not be treated as still applying.
|
|
533
|
+
this.isApplyingRuntimeConfig = false;
|
|
435
534
|
}
|
|
436
|
-
this.isApplyingRuntimeConfig = false;
|
|
437
535
|
this.translationTick.update((value) => value + 1);
|
|
438
536
|
this.logger.debug('setRuntimeConfig - complete', {
|
|
439
537
|
component: 'TranslationService',
|
|
@@ -441,6 +539,57 @@ class TranslationService {
|
|
|
441
539
|
currentLanguage: this.getCurrentLanguage(),
|
|
442
540
|
});
|
|
443
541
|
}
|
|
542
|
+
/**
|
|
543
|
+
* Waits for the fallback language when it differs from the active one, so a key missing in the
|
|
544
|
+
* active language resolves from the fallback on first paint instead of showing the key.
|
|
545
|
+
*/
|
|
546
|
+
async waitForFallbackLanguage() {
|
|
547
|
+
const fallback = this.config.defaultLanguage;
|
|
548
|
+
if (fallback === this.currentLanguage()) {
|
|
549
|
+
return;
|
|
550
|
+
}
|
|
551
|
+
try {
|
|
552
|
+
await firstValueFrom(this.translate.setFallbackLang(fallback));
|
|
553
|
+
}
|
|
554
|
+
catch (error) {
|
|
555
|
+
this.logger.warn('Fallback language failed to load', {
|
|
556
|
+
component: 'TranslationService',
|
|
557
|
+
action: 'setRuntimeConfig',
|
|
558
|
+
language: fallback,
|
|
559
|
+
error: error instanceof Error ? error.message : String(error),
|
|
560
|
+
});
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
/** Languages loaded in ngx-translate (or loading through this service). */
|
|
564
|
+
loadedLanguages() {
|
|
565
|
+
return new Set([...this.knownLanguages, ...this.translate.getLangs()]);
|
|
566
|
+
}
|
|
567
|
+
/**
|
|
568
|
+
* Which languages a refresh fetches again: the active language and the loaded fallback are awaited;
|
|
569
|
+
* every other loaded language that is still available is refreshed in the background. A language
|
|
570
|
+
* never loaded is left alone: ngx-translate loads it with the current paths on first use.
|
|
571
|
+
*/
|
|
572
|
+
planRefresh() {
|
|
573
|
+
const target = this.currentLanguage();
|
|
574
|
+
const fallback = this.config.defaultLanguage;
|
|
575
|
+
const loaded = this.loadedLanguages();
|
|
576
|
+
const available = new Set(this.getAvailableLanguageCodes());
|
|
577
|
+
const awaited = fallback !== target && loaded.has(fallback) && available.has(fallback) ? [target, fallback] : [target];
|
|
578
|
+
const background = [...loaded].filter((lang) => !awaited.includes(lang) && available.has(lang));
|
|
579
|
+
return { awaited, background };
|
|
580
|
+
}
|
|
581
|
+
/** Merges each fetched bundle into its language; returns `true` when at least one was merged. */
|
|
582
|
+
mergeBundles(languages, bundles) {
|
|
583
|
+
let merged = false;
|
|
584
|
+
languages.forEach((lang, index) => {
|
|
585
|
+
const bundle = bundles[index];
|
|
586
|
+
if (bundle) {
|
|
587
|
+
this.applyBundle(lang, bundle);
|
|
588
|
+
merged = true;
|
|
589
|
+
}
|
|
590
|
+
});
|
|
591
|
+
return merged;
|
|
592
|
+
}
|
|
444
593
|
async refreshRuntimeConfig(config) {
|
|
445
594
|
this.logger.debug('setRuntimeConfig - refreshing loaded translations', {
|
|
446
595
|
component: 'TranslationService',
|
|
@@ -449,18 +598,19 @@ class TranslationService {
|
|
|
449
598
|
});
|
|
450
599
|
const refresh = ++this.bundleRefreshId;
|
|
451
600
|
this.isApplyingRuntimeConfig = true;
|
|
601
|
+
const loadedBefore = this.loadedLanguages();
|
|
452
602
|
let switchedLanguage = null;
|
|
603
|
+
let plan = { awaited: [], background: [] };
|
|
453
604
|
try {
|
|
454
605
|
this.configure(config);
|
|
455
606
|
const targetLang = this.currentLanguage();
|
|
456
607
|
const languageUnchanged = this.translate.getCurrentLang() === targetLang;
|
|
457
|
-
|
|
608
|
+
plan = this.planRefresh();
|
|
609
|
+
const bundles = await Promise.all(plan.awaited.map((lang) => this.fetchAwaitedBundle(lang)));
|
|
458
610
|
if (refresh !== this.bundleRefreshId) {
|
|
459
611
|
return;
|
|
460
612
|
}
|
|
461
|
-
|
|
462
|
-
this.translate.setTranslation(targetLang, bundle, true);
|
|
463
|
-
}
|
|
613
|
+
const merged = this.mergeBundles(plan.awaited, bundles);
|
|
464
614
|
if (this.currentLanguage() !== targetLang) {
|
|
465
615
|
switchedLanguage = this.currentLanguage();
|
|
466
616
|
}
|
|
@@ -469,22 +619,53 @@ class TranslationService {
|
|
|
469
619
|
}
|
|
470
620
|
else {
|
|
471
621
|
this.translate.setFallbackLang(this.config.defaultLanguage);
|
|
472
|
-
if (
|
|
622
|
+
if (merged) {
|
|
473
623
|
this.announceRefreshedLanguage(targetLang);
|
|
474
624
|
}
|
|
475
625
|
}
|
|
476
|
-
if (this.prefetchLanguages) {
|
|
477
|
-
this.prefetchRemainingLanguages();
|
|
478
|
-
}
|
|
479
626
|
}
|
|
480
627
|
finally {
|
|
481
628
|
if (refresh === this.bundleRefreshId) {
|
|
482
629
|
this.isApplyingRuntimeConfig = false;
|
|
483
630
|
}
|
|
484
631
|
}
|
|
485
|
-
if
|
|
632
|
+
// A language switched to during the fetch: if it was loaded before, its bundle has the old paths;
|
|
633
|
+
// if not, ngx-translate is loading it now with the new paths and fetching it twice is wasted.
|
|
634
|
+
if (switchedLanguage && loadedBefore.has(switchedLanguage) && !plan.awaited.includes(switchedLanguage)) {
|
|
486
635
|
void this.refreshLoadedLanguage(switchedLanguage);
|
|
487
636
|
}
|
|
637
|
+
this.refreshInBackground(plan.background.filter((lang) => lang !== switchedLanguage));
|
|
638
|
+
}
|
|
639
|
+
/** Refreshes every loaded language after the paths changed outside a runtime config (`configure()`). */
|
|
640
|
+
async refreshLoadedBundles() {
|
|
641
|
+
const refresh = ++this.bundleRefreshId;
|
|
642
|
+
const plan = this.planRefresh();
|
|
643
|
+
const bundles = await Promise.all(plan.awaited.map((lang) => this.fetchAwaitedBundle(lang)));
|
|
644
|
+
if (refresh !== this.bundleRefreshId) {
|
|
645
|
+
return;
|
|
646
|
+
}
|
|
647
|
+
if (this.mergeBundles(plan.awaited, bundles)) {
|
|
648
|
+
this.announceRefreshedLanguage(this.currentLanguage());
|
|
649
|
+
}
|
|
650
|
+
this.refreshInBackground(plan.background);
|
|
651
|
+
}
|
|
652
|
+
refreshInBackground(languages) {
|
|
653
|
+
for (const lang of languages) {
|
|
654
|
+
void this.refreshLanguageInBackground(lang);
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
/**
|
|
658
|
+
* Fetches one language and merges it (the latest fetch per language wins). When it is the active or
|
|
659
|
+
* the fallback language, `onLangChange`, `changes()` and `onLanguageChange` tick so views built from
|
|
660
|
+
* them (menus, labels) pick the new keys up.
|
|
661
|
+
*/
|
|
662
|
+
async refreshLanguageInBackground(lang) {
|
|
663
|
+
if (!(await this.swapTranslations(lang))) {
|
|
664
|
+
return;
|
|
665
|
+
}
|
|
666
|
+
if (lang === this.currentLanguage() || lang === this.config.defaultLanguage) {
|
|
667
|
+
this.announceRefreshedLanguage(this.currentLanguage());
|
|
668
|
+
}
|
|
488
669
|
}
|
|
489
670
|
async refreshLoadedLanguage(lang) {
|
|
490
671
|
const refresh = ++this.bundleRefreshId;
|
|
@@ -492,7 +673,7 @@ class TranslationService {
|
|
|
492
673
|
if (!bundle || refresh !== this.bundleRefreshId) {
|
|
493
674
|
return;
|
|
494
675
|
}
|
|
495
|
-
this.
|
|
676
|
+
this.applyBundle(lang, bundle);
|
|
496
677
|
if (this.currentLanguage() === lang) {
|
|
497
678
|
this.announceRefreshedLanguage(lang);
|
|
498
679
|
}
|
|
@@ -527,60 +708,53 @@ class TranslationService {
|
|
|
527
708
|
return null;
|
|
528
709
|
}
|
|
529
710
|
}
|
|
711
|
+
/**
|
|
712
|
+
* Stores a refreshed bundle. A bundle the SDK loader read in full replaces the language, so a key
|
|
713
|
+
* removed from a file goes away without a reload; any other bundle (a file failed, or a custom loader)
|
|
714
|
+
* is merged over the loaded one, so the keys of a file that could not be read are kept.
|
|
715
|
+
*/
|
|
716
|
+
applyBundle(lang, bundle) {
|
|
717
|
+
this.translate.setTranslation(lang, bundle, !this.completeBundles.has(bundle));
|
|
718
|
+
this.knownLanguages.add(lang);
|
|
719
|
+
}
|
|
720
|
+
/** Fetches `lang` for a refresh that awaits it; an older background fetch of `lang` landing later is dropped. */
|
|
721
|
+
fetchAwaitedBundle(lang) {
|
|
722
|
+
this.inactiveRefreshIds.set(lang, (this.inactiveRefreshIds.get(lang) ?? 0) + 1);
|
|
723
|
+
return this.fetchBundle(lang);
|
|
724
|
+
}
|
|
725
|
+
/** Fetches and merges `lang`; only the latest fetch per language is applied. Returns `true` when merged. */
|
|
530
726
|
async swapTranslations(lang) {
|
|
531
727
|
const refresh = (this.inactiveRefreshIds.get(lang) ?? 0) + 1;
|
|
532
728
|
this.inactiveRefreshIds.set(lang, refresh);
|
|
533
729
|
const bundle = await this.fetchBundle(lang);
|
|
534
730
|
if (bundle && refresh === this.inactiveRefreshIds.get(lang)) {
|
|
535
|
-
this.
|
|
731
|
+
this.applyBundle(lang, bundle);
|
|
732
|
+
return true;
|
|
536
733
|
}
|
|
734
|
+
return false;
|
|
537
735
|
}
|
|
538
736
|
notifyTranslationsChanged() {
|
|
539
737
|
this.onLanguageChange.update((value) => value + 1);
|
|
540
738
|
this.translationTick.update((value) => value + 1);
|
|
541
739
|
}
|
|
740
|
+
/**
|
|
741
|
+
* @deprecated No effect. Languages load on first use with every translation path, and a refresh
|
|
742
|
+
* updates the languages already loaded; the old prefetch downloaded files without keeping them.
|
|
743
|
+
*/
|
|
542
744
|
enablePrefetch(enable) {
|
|
543
|
-
|
|
544
|
-
}
|
|
545
|
-
async loadSelectedLanguage() {
|
|
546
|
-
const targetLang = this.currentLanguage();
|
|
547
|
-
await this.loadLanguageResources(targetLang);
|
|
548
|
-
}
|
|
549
|
-
prefetchRemainingLanguages() {
|
|
550
|
-
const currentLang = this.currentLanguage();
|
|
551
|
-
const remaining = this.getAvailableLanguagesConfig()
|
|
552
|
-
.map((lang) => lang.code)
|
|
553
|
-
.filter((code) => code !== currentLang);
|
|
554
|
-
for (const lang of remaining) {
|
|
555
|
-
this.loadLanguageResources(lang).catch(() => undefined);
|
|
556
|
-
}
|
|
557
|
-
}
|
|
558
|
-
async loadLanguageResources(lang) {
|
|
559
|
-
const loadPromises = this.currentTranslationPaths.map((path) => {
|
|
560
|
-
const normalized = path.endsWith('/') ? path : `${path}/`;
|
|
561
|
-
const url = `${normalized}${lang}.json`;
|
|
562
|
-
return this.fetchTranslation(url);
|
|
563
|
-
});
|
|
564
|
-
await Promise.allSettled(loadPromises);
|
|
565
|
-
}
|
|
566
|
-
queueUpdatedLanguage(lang) {
|
|
567
|
-
if (!lang) {
|
|
568
|
-
return;
|
|
569
|
-
}
|
|
570
|
-
this.pendingUpdatedLanguages.add(lang);
|
|
745
|
+
void enable;
|
|
571
746
|
}
|
|
747
|
+
/** Refreshes the given languages that are loaded and available; the others load on first use. */
|
|
572
748
|
async reloadLanguages(languages) {
|
|
573
|
-
const
|
|
574
|
-
if (!unique.length) {
|
|
575
|
-
return;
|
|
576
|
-
}
|
|
749
|
+
const loaded = this.loadedLanguages();
|
|
577
750
|
const available = new Set(this.getAvailableLanguageCodes());
|
|
578
|
-
|
|
751
|
+
const unique = Array.from(new Set(languages)).filter((lang) => lang && available.has(lang) && loaded.has(lang));
|
|
752
|
+
await Promise.all(unique.map((lang) => this.refreshLanguageInBackground(lang)));
|
|
579
753
|
}
|
|
754
|
+
/** Fetches again every loaded language except the active one. Languages never loaded are not requested. */
|
|
580
755
|
async refreshInactiveLanguages() {
|
|
581
756
|
const current = this.currentLanguage();
|
|
582
|
-
|
|
583
|
-
await this.reloadLanguages(nonActive);
|
|
757
|
+
await this.reloadLanguages(this.getAvailableLanguageCodes().filter((lang) => lang !== current));
|
|
584
758
|
}
|
|
585
759
|
async validateBootstrapCache() {
|
|
586
760
|
if (this.bootstrapValidated) {
|
|
@@ -604,9 +778,9 @@ class TranslationService {
|
|
|
604
778
|
this.runtimeHash = result.hash;
|
|
605
779
|
this.runtimeMeta = result.meta;
|
|
606
780
|
this.updateAvailable.set(false);
|
|
781
|
+
// The refresh updates every loaded language, so nothing else is fetched here.
|
|
607
782
|
await this.setRuntimeConfig(result.data);
|
|
608
783
|
this.ready.set(true);
|
|
609
|
-
void this.refreshInactiveLanguages();
|
|
610
784
|
}
|
|
611
785
|
catch (error) {
|
|
612
786
|
this.logger.warn('Translation bootstrap validation failed', {
|
|
@@ -646,6 +820,8 @@ class TranslationService {
|
|
|
646
820
|
}
|
|
647
821
|
applyLanguage() {
|
|
648
822
|
const targetLang = this.currentLanguage();
|
|
823
|
+
this.knownLanguages.add(this.config.defaultLanguage);
|
|
824
|
+
this.knownLanguages.add(targetLang);
|
|
649
825
|
this.translate.setFallbackLang(this.config.defaultLanguage);
|
|
650
826
|
this.translate.use(targetLang);
|
|
651
827
|
this.domService.setDocumentLanguage(targetLang);
|
|
@@ -672,8 +848,14 @@ class TranslationService {
|
|
|
672
848
|
action: 'setLanguage',
|
|
673
849
|
language: lang,
|
|
674
850
|
});
|
|
851
|
+
// A language whose last load had a file that could not be read is fetched again now that it is
|
|
852
|
+
// in use: the new language, and the fallback that fills its missing keys.
|
|
853
|
+
const retry = [lang, this.config.defaultLanguage].filter((code, index, all) => all.indexOf(code) === index && this.incompleteLanguages.has(code));
|
|
675
854
|
this.currentLanguage.set(lang);
|
|
676
855
|
this.applyLanguage();
|
|
856
|
+
for (const code of retry) {
|
|
857
|
+
void this.refreshLanguageInBackground(code);
|
|
858
|
+
}
|
|
677
859
|
}
|
|
678
860
|
}
|
|
679
861
|
getCurrentLanguage() {
|
|
@@ -699,8 +881,9 @@ class TranslationService {
|
|
|
699
881
|
}
|
|
700
882
|
return localeConfig.defaultLocale ?? DEFAULT_TRANSLATION_LOCALE_CONFIG.defaultLocale ?? DEFAULT_LANGUAGE_CODE;
|
|
701
883
|
}
|
|
884
|
+
/** The configured language codes (as `getAvailableLanguageCodes()`), not only the ones loaded so far. */
|
|
702
885
|
getAvailableLanguages() {
|
|
703
|
-
return
|
|
886
|
+
return this.getAvailableLanguageCodes();
|
|
704
887
|
}
|
|
705
888
|
getDefaultLanguage() {
|
|
706
889
|
return this.config.defaultLanguage;
|
|
@@ -842,12 +1025,10 @@ class TranslationService {
|
|
|
842
1025
|
return;
|
|
843
1026
|
}
|
|
844
1027
|
const eventHash = event?.hash;
|
|
845
|
-
const eventLang = event && 'lang' in event ? event.lang : undefined;
|
|
846
1028
|
if (eventHash) {
|
|
847
1029
|
if (eventHash === this.runtimeHash) {
|
|
848
1030
|
return;
|
|
849
1031
|
}
|
|
850
|
-
this.queueUpdatedLanguage(eventLang);
|
|
851
1032
|
if (!this.updateAvailable()) {
|
|
852
1033
|
this.updateAvailable.set(true);
|
|
853
1034
|
}
|
|
@@ -876,13 +1057,9 @@ class TranslationService {
|
|
|
876
1057
|
}
|
|
877
1058
|
try {
|
|
878
1059
|
const result = await runtimeLoader.refresh();
|
|
1060
|
+
// The refresh fetches every loaded language again (the active one and the fallback awaited), so a
|
|
1061
|
+
// language named by an update event needs no separate reload; one never loaded loads on first use.
|
|
879
1062
|
await this.applyRuntimeConfig(result, runtimeLoader);
|
|
880
|
-
const pendingLanguages = Array.from(this.pendingUpdatedLanguages);
|
|
881
|
-
this.pendingUpdatedLanguages.clear();
|
|
882
|
-
const current = this.currentLanguage();
|
|
883
|
-
if (pendingLanguages.length > 0) {
|
|
884
|
-
await this.reloadLanguages(pendingLanguages.filter((lang) => lang !== current));
|
|
885
|
-
}
|
|
886
1063
|
this.updateAvailable.set(false);
|
|
887
1064
|
this.lastRefreshFailed.set(false);
|
|
888
1065
|
}
|
|
@@ -903,52 +1080,79 @@ class TranslationService {
|
|
|
903
1080
|
}
|
|
904
1081
|
getOrCreateHttpClient() {
|
|
905
1082
|
if (!this.translationHttpClient) {
|
|
1083
|
+
// One quick retry for a transient error. A file that still fails marks its language incomplete
|
|
1084
|
+
// and is fetched again on next use or registration, so a failing remote does not hold a route
|
|
1085
|
+
// guard for long (worst case about 4.3 s for errors, 8.3 s for a server that hangs).
|
|
906
1086
|
this.translationHttpClient = new RuntimeHttpClient({
|
|
907
|
-
retries:
|
|
908
|
-
retryDelayMs:
|
|
909
|
-
timeoutMs:
|
|
1087
|
+
retries: 1,
|
|
1088
|
+
retryDelayMs: 300,
|
|
1089
|
+
timeoutMs: 4000,
|
|
1090
|
+
// A language file that does not exist (e.g. a remote without `pt.json`) is not retried.
|
|
1091
|
+
noRetryStatuses: [404],
|
|
910
1092
|
});
|
|
911
1093
|
}
|
|
912
1094
|
return this.translationHttpClient;
|
|
913
1095
|
}
|
|
1096
|
+
/** Reads one language file. A 404 is a file that does not exist (empty, not a failure). */
|
|
914
1097
|
async fetchTranslation(url) {
|
|
915
1098
|
try {
|
|
916
1099
|
const response = await this.getOrCreateHttpClient().fetch(url, { cache: 'no-store' });
|
|
917
|
-
return (await response.json());
|
|
1100
|
+
return { bundle: (await response.json()), failed: false };
|
|
918
1101
|
}
|
|
919
|
-
catch {
|
|
920
|
-
|
|
1102
|
+
catch (error) {
|
|
1103
|
+
if (error instanceof RuntimeHttpError && error.status === 404) {
|
|
1104
|
+
return { bundle: {}, failed: false };
|
|
1105
|
+
}
|
|
1106
|
+
this.logger.warn('Translation file could not be read', {
|
|
1107
|
+
component: 'TranslationService',
|
|
1108
|
+
action: 'fetchTranslation',
|
|
1109
|
+
url,
|
|
1110
|
+
error: error instanceof Error ? error.message : String(error),
|
|
1111
|
+
});
|
|
1112
|
+
return { bundle: {}, failed: true };
|
|
1113
|
+
}
|
|
1114
|
+
}
|
|
1115
|
+
/**
|
|
1116
|
+
* Loads one language from every translation path and merges the files in path order. When the paths
|
|
1117
|
+
* change while it fetches (e.g. a remote's folder is added), it fetches again with the new paths, so
|
|
1118
|
+
* ngx-translate, which stores a load result over the language, never keeps a bundle missing them.
|
|
1119
|
+
*/
|
|
1120
|
+
async loadLanguageBundle(lang) {
|
|
1121
|
+
this.knownLanguages.add(lang);
|
|
1122
|
+
for (let attempt = 0;; attempt += 1) {
|
|
1123
|
+
const epoch = this.pathsEpoch;
|
|
1124
|
+
const paths = this.currentTranslationPaths;
|
|
1125
|
+
this.logger.debug('TranslateLoader.getTranslation called', { language: lang, pathsToUse: paths });
|
|
1126
|
+
if (paths.length === 0) {
|
|
1127
|
+
this.logger.warn('No translation paths configured', { language: lang });
|
|
1128
|
+
return {};
|
|
1129
|
+
}
|
|
1130
|
+
const results = await Promise.all(paths.map((path) => this.fetchTranslation(`${normalizeTranslationPath(path)}${lang}.json`)));
|
|
1131
|
+
if (epoch !== this.pathsEpoch && attempt < MAX_PATH_CHANGE_RESTARTS) {
|
|
1132
|
+
continue;
|
|
1133
|
+
}
|
|
1134
|
+
// A failed file, or paths that kept changing past the restarts: fetch it again on next use.
|
|
1135
|
+
if (results.some((result) => result.failed) || epoch !== this.pathsEpoch) {
|
|
1136
|
+
this.incompleteLanguages.add(lang);
|
|
1137
|
+
}
|
|
1138
|
+
else {
|
|
1139
|
+
this.incompleteLanguages.delete(lang);
|
|
1140
|
+
}
|
|
1141
|
+
const merged = results.reduce((acc, result) => this.deepMergeTranslations(acc, result.bundle), {});
|
|
1142
|
+
if (!this.incompleteLanguages.has(lang)) {
|
|
1143
|
+
this.completeBundles.add(merged);
|
|
1144
|
+
}
|
|
1145
|
+
this.logger.debug('Translations loaded and merged', {
|
|
1146
|
+
language: lang,
|
|
1147
|
+
filesLoaded: results.length,
|
|
1148
|
+
totalKeys: Object.keys(merged).length,
|
|
1149
|
+
});
|
|
1150
|
+
return merged;
|
|
921
1151
|
}
|
|
922
1152
|
}
|
|
923
1153
|
createTranslateLoader() {
|
|
924
|
-
const suffix = '.json';
|
|
925
1154
|
return {
|
|
926
|
-
getTranslation: (lang) =>
|
|
927
|
-
this.logger.debug('TranslateLoader.getTranslation called', {
|
|
928
|
-
language: lang,
|
|
929
|
-
pathsToUse: this.currentTranslationPaths,
|
|
930
|
-
});
|
|
931
|
-
const pathsToUse = this.currentTranslationPaths;
|
|
932
|
-
if (pathsToUse.length === 0) {
|
|
933
|
-
this.logger.warn('No translation paths configured', { language: lang });
|
|
934
|
-
return from(Promise.resolve({}));
|
|
935
|
-
}
|
|
936
|
-
const loadPromises = pathsToUse.map((path) => {
|
|
937
|
-
const url = `${path.endsWith('/') ? path : `${path}/`}${lang}${suffix}`;
|
|
938
|
-
return this.fetchTranslation(url);
|
|
939
|
-
});
|
|
940
|
-
return from(Promise.all(loadPromises).then((results) => {
|
|
941
|
-
const merged = results.reduce((acc, result) => {
|
|
942
|
-
return this.deepMergeTranslations(acc, result ?? {});
|
|
943
|
-
}, {});
|
|
944
|
-
this.logger.debug('Translations loaded and merged', {
|
|
945
|
-
language: lang,
|
|
946
|
-
filesLoaded: results.length,
|
|
947
|
-
totalKeys: Object.keys(merged).length,
|
|
948
|
-
});
|
|
949
|
-
return merged;
|
|
950
|
-
}));
|
|
951
|
-
},
|
|
1155
|
+
getTranslation: (lang) => from(this.loadLanguageBundle(lang)),
|
|
952
1156
|
};
|
|
953
1157
|
}
|
|
954
1158
|
isTranslationObject(value) {
|
|
@@ -1133,24 +1337,49 @@ function deepestDataTitle(route) {
|
|
|
1133
1337
|
/**
|
|
1134
1338
|
* Sets the tab title to the translated title of the active route: the route `title` property first,
|
|
1135
1339
|
* then `data.title` of the deepest route (the source page headers read), then `fallbackKey`.
|
|
1340
|
+
*
|
|
1341
|
+
* The title follows a language switch and translations loaded later (e.g. a remote's keys) without a
|
|
1342
|
+
* navigation. It is translated again only while the tab still shows the text this strategy set, so a
|
|
1343
|
+
* title a page set on its own (see `skip`) is left alone.
|
|
1136
1344
|
*/
|
|
1137
1345
|
class TranslatedTitleStrategy extends TitleStrategy {
|
|
1138
1346
|
config = inject(TRANSLATED_TITLE_STRATEGY_CONFIG);
|
|
1139
1347
|
title = inject(Title);
|
|
1140
1348
|
translationService = inject(TranslationService);
|
|
1349
|
+
lastKey = null;
|
|
1350
|
+
lastText = null;
|
|
1351
|
+
constructor() {
|
|
1352
|
+
super();
|
|
1353
|
+
const subscription = this.translationService.onLanguageChange$.subscribe(() => this.retranslate());
|
|
1354
|
+
inject(DestroyRef).onDestroy(() => subscription.unsubscribe());
|
|
1355
|
+
}
|
|
1141
1356
|
updateTitle(snapshot) {
|
|
1142
1357
|
if (this.config.skip?.(snapshot)) {
|
|
1358
|
+
this.lastKey = null;
|
|
1359
|
+
this.lastText = null;
|
|
1143
1360
|
return;
|
|
1144
1361
|
}
|
|
1145
1362
|
const routeTitle = this.buildTitle(snapshot) || deepestDataTitle(snapshot.root);
|
|
1146
|
-
this.
|
|
1363
|
+
this.setTranslatedTitle(routeTitle || this.config.fallbackKey);
|
|
1364
|
+
}
|
|
1365
|
+
retranslate() {
|
|
1366
|
+
if (this.lastKey === null || this.title.getTitle() !== this.lastText) {
|
|
1367
|
+
return;
|
|
1368
|
+
}
|
|
1369
|
+
this.setTranslatedTitle(this.lastKey);
|
|
1370
|
+
}
|
|
1371
|
+
setTranslatedTitle(key) {
|
|
1372
|
+
const text = this.translationService.instant(key);
|
|
1373
|
+
this.lastKey = key;
|
|
1374
|
+
this.lastText = text;
|
|
1375
|
+
this.title.setTitle(text);
|
|
1147
1376
|
}
|
|
1148
|
-
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.25", ngImport: i0, type: TranslatedTitleStrategy, deps:
|
|
1377
|
+
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.25", ngImport: i0, type: TranslatedTitleStrategy, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
|
|
1149
1378
|
static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.25", ngImport: i0, type: TranslatedTitleStrategy });
|
|
1150
1379
|
}
|
|
1151
1380
|
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.25", ngImport: i0, type: TranslatedTitleStrategy, decorators: [{
|
|
1152
1381
|
type: Injectable
|
|
1153
|
-
}] });
|
|
1382
|
+
}], ctorParameters: () => [] });
|
|
1154
1383
|
/** Replaces the router's `TitleStrategy` with `TranslatedTitleStrategy`. */
|
|
1155
1384
|
function provideTranslatedTitleStrategy(config) {
|
|
1156
1385
|
return [
|