@sixbell-telco/sdk 1.6.0 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/CHANGELOG.md +196 -711
  2. package/README.md +307 -282
  3. package/_index.css +3 -3
  4. package/components/audio-player/audio-timeline/audio-timeline.component.d.ts +1 -1
  5. package/components/audio-player/services/audio.service.d.ts +14 -14
  6. package/components/countdown/src/countdown.component.d.ts +1 -1
  7. package/components/dropdown-menu/src/dropdown-menu-content/dropdown-menu-content.component.d.ts +2 -3
  8. package/components/dual-list/src/dual-list.component.d.ts +2 -1
  9. package/components/file-upload/file-dropzone/file-dropzone.component.d.ts +7 -7
  10. package/components/file-upload/file-uploader/file-uploader.component.d.ts +7 -7
  11. package/components/forms/input/src/input.component.d.ts +11 -1
  12. package/components/forms/textarea/src/textarea.component.d.ts +10 -10
  13. package/components/link/src/link.component.d.ts +0 -3
  14. package/components/tab/directives/tab-content/tab-content.directive.d.ts +3 -3
  15. package/components/tab/directives/tab-header/tab-header.directive.d.ts +2 -2
  16. package/components/wizard/services/wizard.service.d.ts +5 -5
  17. package/directives/auto-focus/public-api.d.ts +1 -1
  18. package/directives/auto-focus/src/{autofocus.directive.d.ts → auto-focus.directive.d.ts} +5 -7
  19. package/directives/only-numbers/public-api.d.ts +6 -1
  20. package/directives/only-numbers/src/only-numbers.directive.d.ts +37 -0
  21. package/fesm2022/sixbell-telco-sdk-components-audio-player.mjs +7 -5
  22. package/fesm2022/sixbell-telco-sdk-components-audio-player.mjs.map +1 -1
  23. package/fesm2022/sixbell-telco-sdk-components-avatar.mjs +1 -1
  24. package/fesm2022/sixbell-telco-sdk-components-avatar.mjs.map +1 -1
  25. package/fesm2022/sixbell-telco-sdk-components-badge.mjs +2 -2
  26. package/fesm2022/sixbell-telco-sdk-components-badge.mjs.map +1 -1
  27. package/fesm2022/sixbell-telco-sdk-components-countdown.mjs.map +1 -1
  28. package/fesm2022/sixbell-telco-sdk-components-data-table.mjs +2 -2
  29. package/fesm2022/sixbell-telco-sdk-components-data-table.mjs.map +1 -1
  30. package/fesm2022/sixbell-telco-sdk-components-dropdown-menu.mjs +0 -4
  31. package/fesm2022/sixbell-telco-sdk-components-dropdown-menu.mjs.map +1 -1
  32. package/fesm2022/sixbell-telco-sdk-components-dual-list.mjs +8 -7
  33. package/fesm2022/sixbell-telco-sdk-components-dual-list.mjs.map +1 -1
  34. package/fesm2022/sixbell-telco-sdk-components-file-upload.mjs +6 -4
  35. package/fesm2022/sixbell-telco-sdk-components-file-upload.mjs.map +1 -1
  36. package/fesm2022/sixbell-telco-sdk-components-forms-date-picker.mjs +2 -0
  37. package/fesm2022/sixbell-telco-sdk-components-forms-date-picker.mjs.map +1 -1
  38. package/fesm2022/sixbell-telco-sdk-components-forms-input.mjs +15 -5
  39. package/fesm2022/sixbell-telco-sdk-components-forms-input.mjs.map +1 -1
  40. package/fesm2022/sixbell-telco-sdk-components-forms-select.mjs +2 -2
  41. package/fesm2022/sixbell-telco-sdk-components-forms-select.mjs.map +1 -1
  42. package/fesm2022/sixbell-telco-sdk-components-forms-textarea.mjs +19 -8
  43. package/fesm2022/sixbell-telco-sdk-components-forms-textarea.mjs.map +1 -1
  44. package/fesm2022/sixbell-telco-sdk-components-link.mjs +2 -7
  45. package/fesm2022/sixbell-telco-sdk-components-link.mjs.map +1 -1
  46. package/fesm2022/sixbell-telco-sdk-components-overlay.mjs +2 -2
  47. package/fesm2022/sixbell-telco-sdk-components-overlay.mjs.map +1 -1
  48. package/fesm2022/sixbell-telco-sdk-components-tab.mjs.map +1 -1
  49. package/fesm2022/sixbell-telco-sdk-components-wizard.mjs.map +1 -1
  50. package/fesm2022/sixbell-telco-sdk-directives-auto-focus.mjs +14 -31
  51. package/fesm2022/sixbell-telco-sdk-directives-auto-focus.mjs.map +1 -1
  52. package/fesm2022/sixbell-telco-sdk-directives-only-numbers.mjs +42 -8
  53. package/fesm2022/sixbell-telco-sdk-directives-only-numbers.mjs.map +1 -1
  54. package/fesm2022/sixbell-telco-sdk-utils-date.mjs +1 -1
  55. package/fesm2022/sixbell-telco-sdk-utils-date.mjs.map +1 -1
  56. package/fesm2022/sixbell-telco-sdk-utils-pipes-to-bytes-extesion.mjs +1 -1
  57. package/fesm2022/sixbell-telco-sdk-utils-pipes-to-bytes-extesion.mjs.map +1 -1
  58. package/fesm2022/sixbell-telco-sdk-utils-runtime-config.mjs +339 -0
  59. package/fesm2022/sixbell-telco-sdk-utils-runtime-config.mjs.map +1 -0
  60. package/fesm2022/sixbell-telco-sdk-utils-sync.mjs +1 -1
  61. package/fesm2022/sixbell-telco-sdk-utils-sync.mjs.map +1 -1
  62. package/fesm2022/sixbell-telco-sdk-utils-theme.mjs +1053 -716
  63. package/fesm2022/sixbell-telco-sdk-utils-theme.mjs.map +1 -1
  64. package/fesm2022/sixbell-telco-sdk-utils-translation.mjs +345 -257
  65. package/fesm2022/sixbell-telco-sdk-utils-translation.mjs.map +1 -1
  66. package/package.json +67 -66
  67. package/utils/runtime-config/README.md +235 -0
  68. package/utils/{resource-loader → runtime-config}/index.d.ts +1 -1
  69. package/utils/runtime-config/public-api.d.ts +5 -0
  70. package/utils/runtime-config/src/http-client.d.ts +11 -0
  71. package/utils/runtime-config/src/runtime-config-loader.d.ts +23 -0
  72. package/utils/runtime-config/src/runtime-config-store.d.ts +11 -0
  73. package/utils/runtime-config/src/runtime-update-adapter.d.ts +15 -0
  74. package/utils/runtime-config/src/types.d.ts +66 -0
  75. package/utils/theme/README.md +324 -986
  76. package/utils/theme/public-api.d.ts +4 -4
  77. package/utils/theme/src/constants.d.ts +6 -12
  78. package/utils/theme/src/models/theme.d.ts +46 -173
  79. package/utils/theme/src/providers/theme.provider.d.ts +0 -10
  80. package/utils/theme/src/providers/theme.provider.types.d.ts +16 -15
  81. package/utils/theme/src/theme-assets/theme-assets.service.d.ts +16 -12
  82. package/utils/theme/src/theme-dom/theme-dom.service.d.ts +8 -0
  83. package/utils/theme/src/theme.service.d.ts +24 -27
  84. package/utils/theme/src/utils/utils.d.ts +2 -10
  85. package/utils/translation/README.md +170 -1390
  86. package/utils/translation/public-api.d.ts +3 -3
  87. package/utils/translation/src/constants.d.ts +7 -9
  88. package/utils/translation/src/models/translation.d.ts +9 -10
  89. package/utils/translation/src/providers/translation.provider.d.ts +17 -28
  90. package/utils/translation/src/providers/translation.provider.types.d.ts +13 -6
  91. package/utils/translation/src/translation.service.d.ts +37 -9
  92. package/directives/only-numbers/src/just-numbers.directive.d.ts +0 -9
  93. package/fesm2022/sixbell-telco-sdk-utils-resource-loader.mjs +0 -1222
  94. package/fesm2022/sixbell-telco-sdk-utils-resource-loader.mjs.map +0 -1
  95. package/utils/resource-loader/README.md +0 -460
  96. package/utils/resource-loader/public-api.d.ts +0 -1
  97. package/utils/resource-loader/src/cache/index.d.ts +0 -2
  98. package/utils/resource-loader/src/cache/layers/factory.d.ts +0 -38
  99. package/utils/resource-loader/src/cache/layers/index.d.ts +0 -3
  100. package/utils/resource-loader/src/cache/layers/indexed-db-cache.d.ts +0 -118
  101. package/utils/resource-loader/src/cache/layers/local-storage-cache.d.ts +0 -86
  102. package/utils/resource-loader/src/cache/layers/memory-cache.d.ts +0 -76
  103. package/utils/resource-loader/src/cache/types.d.ts +0 -107
  104. package/utils/resource-loader/src/config/index.d.ts +0 -1
  105. package/utils/resource-loader/src/config/load-config.d.ts +0 -32
  106. package/utils/resource-loader/src/constants.d.ts +0 -38
  107. package/utils/resource-loader/src/http/index.d.ts +0 -1
  108. package/utils/resource-loader/src/http/retryable-client.d.ts +0 -43
  109. package/utils/resource-loader/src/index.d.ts +0 -1
  110. package/utils/resource-loader/src/resource-loader.d.ts +0 -67
  111. package/utils/resource-loader/src/types.d.ts +0 -152
  112. package/utils/resource-loader/src/utils/cache-validator.d.ts +0 -72
  113. package/utils/resource-loader/src/utils/helpers.d.ts +0 -15
  114. package/utils/resource-loader/src/utils/index.d.ts +0 -2
  115. package/utils/theme/src/providers/constants.d.ts +0 -7
  116. package/utils/translation/src/providers/constants.d.ts +0 -11
@@ -1,10 +1,8 @@
1
1
  import * as i0 from '@angular/core';
2
- import { InjectionToken, signal, inject, Injectable, Inject, computed, Optional, makeEnvironmentProviders, provideAppInitializer } from '@angular/core';
2
+ import { inject, Injectable, signal, Inject, computed, makeEnvironmentProviders, provideAppInitializer } from '@angular/core';
3
3
  import { LoggerService } from '@sixbell-telco/sdk/utils/logger';
4
- import { ResourceLoader } from '@sixbell-telco/sdk/utils/resource-loader';
5
- import { Router, NavigationEnd } from '@angular/router';
4
+ import { RuntimeConfigStore, RuntimeConfigLoader, RuntimeUpdateAdapter } from '@sixbell-telco/sdk/utils/runtime-config';
6
5
  import { TranslationService } from '@sixbell-telco/sdk/utils/translation';
7
- import { filter } from 'rxjs/operators';
8
6
  import { DOCUMENT } from '@angular/common';
9
7
 
10
8
  /**
@@ -49,6 +47,11 @@ const THEME_SCHEME_SEPARATOR = '__';
49
47
  * Default theme scheme preference
50
48
  */
51
49
  const DEFAULT_SCHEME = 'system';
50
+ /**
51
+ * Schema version for runtime theme configuration payloads.
52
+ * Bump this when the JSON structure changes in a breaking way.
53
+ */
54
+ const THEME_SCHEMA_VERSION = '2';
52
55
  /**
53
56
  * All valid scheme values
54
57
  */
@@ -57,15 +60,29 @@ const VALID_SCHEMES = ['system', 'light', 'dark'];
57
60
  * Minimal runtime configuration used as a resilient fallback when remote loading fails
58
61
  */
59
62
  const FALLBACK_RUNTIME_THEME_CONFIG = {
63
+ meta: {
64
+ name: DEFAULT_BASE_THEME,
65
+ updatedAt: new Date().toISOString(),
66
+ hash: 'fallback-hash',
67
+ schemaVersion: THEME_SCHEMA_VERSION,
68
+ },
69
+ fonts: [
70
+ {
71
+ family: 'Poppins',
72
+ faces: [
73
+ { weight: 400, style: 'normal', src: '/assets/fonts/Poppins-Regular.ttf' },
74
+ { weight: 500, style: 'normal', src: '/assets/fonts/Poppins-Medium.ttf' },
75
+ { weight: 600, style: 'normal', src: '/assets/fonts/Poppins-SemiBold.ttf' },
76
+ { weight: 700, style: 'normal', src: '/assets/fonts/Poppins-Bold.ttf' },
77
+ { weight: 800, style: 'normal', src: '/assets/fonts/Poppins-ExtraBold.ttf' },
78
+ { weight: 900, style: 'normal', src: '/assets/fonts/Poppins-Black.ttf' },
79
+ ],
80
+ },
81
+ ],
60
82
  themes: {
61
- [DEFAULT_BASE_THEME]: {
62
- light: {
63
- daisyuiName: `${DEFAULT_BASE_THEME}__light`,
64
- prefersDark: false,
65
- variables: {
66
- '--font-poppins': 'Poppins, sans-serif',
67
- '--font-heading': 'Poppins, sans-serif',
68
- '--font-body': 'Poppins, sans-serif',
83
+ light: {
84
+ variables: {
85
+ colors: {
69
86
  '--color-base-100': 'oklch(96.65% 0.0045 258.32)',
70
87
  '--color-base-200': 'oklch(100% 0 0)',
71
88
  '--color-base-300': 'oklch(92.88% 0.0126 255.51)',
@@ -115,23 +132,31 @@ const FALLBACK_RUNTIME_THEME_CONFIG = {
115
132
  '--color-metrics-intensity-low': 'oklch(76.18% 0.0656 213.66)',
116
133
  '--color-metrics-intensity-lowest': 'oklch(78% 0.0473 211.88)',
117
134
  '--color-scroll-thumb': 'oklch(75% 0 0)',
135
+ },
136
+ radius: {
118
137
  '--radius-selector': '0.5rem',
119
138
  '--radius-field': '0.25rem',
120
139
  '--radius-box': '0.5rem',
140
+ },
141
+ sizes: {
121
142
  '--size-selector': '0.25rem',
122
143
  '--size-field': '0.25rem',
144
+ },
145
+ effects: {
123
146
  '--border': '1px',
124
147
  '--depth': '0',
125
148
  '--noise': '0',
126
149
  },
127
- },
128
- dark: {
129
- daisyuiName: `${DEFAULT_BASE_THEME}__dark`,
130
- prefersDark: true,
131
- variables: {
150
+ others: {
132
151
  '--font-poppins': 'Poppins, sans-serif',
133
152
  '--font-heading': 'Poppins, sans-serif',
134
153
  '--font-body': 'Poppins, sans-serif',
154
+ },
155
+ },
156
+ },
157
+ dark: {
158
+ variables: {
159
+ colors: {
135
160
  '--color-base-100': 'oklch(18.22% 0 0)',
136
161
  '--color-base-200': 'oklch(23.5% 0 0)',
137
162
  '--color-base-300': 'oklch(28.5% 0 0)',
@@ -181,21 +206,36 @@ const FALLBACK_RUNTIME_THEME_CONFIG = {
181
206
  '--color-metrics-intensity-low': 'oklch(76.18% 0.0656 213.66)',
182
207
  '--color-metrics-intensity-lowest': 'oklch(78% 0.0473 211.88)',
183
208
  '--color-scroll-thumb': 'oklch(35% 0 0)',
209
+ },
210
+ radius: {
184
211
  '--radius-selector': '0.5rem',
185
212
  '--radius-field': '0.25rem',
186
213
  '--radius-box': '0.5rem',
214
+ },
215
+ sizes: {
187
216
  '--size-selector': '0.25rem',
188
217
  '--size-field': '0.25rem',
218
+ },
219
+ effects: {
189
220
  '--border': '1px',
190
221
  '--depth': '0',
191
222
  '--noise': '0',
192
223
  },
224
+ others: {
225
+ '--font-poppins': 'Poppins, sans-serif',
226
+ '--font-heading': 'Poppins, sans-serif',
227
+ '--font-body': 'Poppins, sans-serif',
228
+ },
193
229
  },
194
230
  },
195
231
  },
196
- availableThemes: [DEFAULT_BASE_THEME],
197
- defaultTheme: DEFAULT_BASE_THEME,
198
- defaultScheme: DEFAULT_SCHEME,
232
+ assets: [
233
+ {
234
+ name: 'logo',
235
+ light: '/assets/logos/sixbell-logo-light-mode.svg',
236
+ dark: '/assets/logos/sixbell-logo-dark-mode.svg',
237
+ },
238
+ ],
199
239
  };
200
240
  /**
201
241
  * CSS class name applied to document when dark theme is detected
@@ -205,182 +245,406 @@ const DARK_THEME_CLASS = 'dark';
205
245
  * Media query for detecting system dark mode preference
206
246
  */
207
247
  const DARK_MODE_MEDIA_QUERY = '(prefers-color-scheme: dark)';
248
+
249
+ /**
250
+ * Theme Utility Functions
251
+ * Pure, side-effect-free utilities for theme logic
252
+ */
253
+ /**
254
+ * Validates that a given value is a valid theme scheme
255
+ * @param value - The value to validate
256
+ * @returns True if the value is a valid scheme ('system', 'light', or 'dark')
257
+ */
258
+ function isValidScheme(value) {
259
+ return typeof value === 'string' && VALID_SCHEMES.includes(value);
260
+ }
261
+ /**
262
+ * Builds the final theme identifier by combining theme name and scheme
263
+ * @param themeName - The name of the theme
264
+ * @param scheme - The scheme variant (light or dark)
265
+ * @returns Combined identifier (e.g., "sixbell_telco__light")
266
+ */
267
+ function buildThemeIdentifier(themeName, scheme) {
268
+ return `${themeName}__${scheme}`;
269
+ }
270
+ /**
271
+ * Extracts theme name and scheme from a combined identifier
272
+ * @param identifier - The combined identifier (e.g., "sixbell_telco__light")
273
+ * @returns Object with extracted themeName and scheme
274
+ */
275
+ function parseThemeIdentifier(identifier) {
276
+ const [themeName, scheme] = identifier.split('__');
277
+ return { themeName, scheme };
278
+ }
279
+ /**
280
+ * Determines the effective default theme from configuration
281
+ * Ensures the default theme is in the available themes list
282
+ * Falls back to first available theme if default is not available
283
+ * @param defaultTheme - Configured default theme
284
+ * @param availableThemes - List of available themes
285
+ * @returns The effective default theme to use
286
+ */
287
+ function resolveDefaultTheme(defaultTheme, availableThemes) {
288
+ // Use provided default if valid
289
+ if (defaultTheme && availableThemes.includes(defaultTheme)) {
290
+ return defaultTheme;
291
+ }
292
+ // Check if base theme is available
293
+ if (availableThemes.includes(DEFAULT_BASE_THEME)) {
294
+ return DEFAULT_BASE_THEME;
295
+ }
296
+ // Fallback to first available
297
+ return availableThemes[0] || DEFAULT_BASE_THEME;
298
+ }
299
+ /**
300
+ * Validates that a given theme exists in the available themes
301
+ * @param theme - Theme name to validate
302
+ * @param availableThemes - List of available themes
303
+ * @returns True if theme is available
304
+ */
305
+ function isThemeAvailable(theme, availableThemes) {
306
+ return availableThemes.includes(theme);
307
+ }
308
+ /**
309
+ * Validates the configuration and logs warnings for invalid states
310
+ * Returns true if configuration is valid for use
311
+ * @param config - Configuration to validate
312
+ * @param configName - Name of config for logging purposes
313
+ * @returns True if configuration is valid
314
+ */
315
+ function validateThemeConfig(config, configName = 'ThemeConfig') {
316
+ const errors = [];
317
+ if (!config.availableThemes || config.availableThemes.length === 0) {
318
+ errors.push('availableThemes must be a non-empty array');
319
+ }
320
+ if (!config.defaultTheme) {
321
+ errors.push('defaultTheme must be defined');
322
+ }
323
+ if (config.defaultTheme && !config.availableThemes.includes(config.defaultTheme)) {
324
+ errors.push(`defaultTheme '${config.defaultTheme}' not in availableThemes`);
325
+ }
326
+ if (errors.length > 0) {
327
+ console.error(`${configName} validation failed:`, errors.join(', '));
328
+ return false;
329
+ }
330
+ return true;
331
+ }
332
+ /**
333
+ * Formats a theme name for display to users
334
+ * Converts snake_case to Title Case
335
+ * @param theme - Theme name to format
336
+ * @returns Formatted theme name
337
+ */
338
+ function formatThemeName(theme) {
339
+ return theme.replace(/_/g, ' ').replace(/\b\w/g, (l) => l.toUpperCase());
340
+ }
341
+ /**
342
+ * Formats a scheme name for display to users
343
+ * Capitalizes first letter
344
+ * @param scheme - Scheme name to format
345
+ * @returns Formatted scheme name
346
+ */
347
+ function formatSchemeName(scheme) {
348
+ return scheme.charAt(0).toUpperCase() + scheme.slice(1);
349
+ }
208
350
  /**
209
- * Injection token for theme configuration
210
- * Used to provide static theme configuration at bootstrap
351
+ * Checks if the browser supports the matchMedia API
352
+ * Safe to call in non-browser environments
353
+ * @returns True if matchMedia is available
211
354
  */
212
- const THEME_CONFIG_TOKEN = new InjectionToken('Theme Configuration');
355
+ function supportsMediaQuery() {
356
+ return typeof window !== 'undefined' && typeof window.matchMedia === 'function';
357
+ }
213
358
  /**
214
- * Injection token for runtime theme configuration
215
- * Used to provide dynamic runtime theme configuration loaded from JSON file
359
+ * Checks if localStorage is available in the current environment
360
+ * Safe to call in non-browser environments
361
+ * @returns True if localStorage is accessible
216
362
  */
217
- const RUNTIME_THEME_CONFIG_TOKEN = new InjectionToken('Runtime Theme Configuration');
363
+ function hasLocalStorage() {
364
+ try {
365
+ return typeof window !== 'undefined' && typeof localStorage !== 'undefined' && localStorage !== null;
366
+ }
367
+ catch {
368
+ return false;
369
+ }
370
+ }
218
371
 
219
372
  /**
220
- * Theme Assets Service
221
- * Manages dynamic asset loading and retrieval based on selected theme and color scheme
222
- *
223
- * Responsibilities:
224
- * - Retrieve assets (images, logos, illustrations) for current theme
225
- * - Provide scheme-aware asset variants (light/dark)
226
- * - Cache asset references with config-based resilience strategy
227
- * - Validate asset availability and provide graceful fallback through memory layers
228
- *
229
- * Multi-Layer Caching Strategy (Like Theme Config Persistence):
230
- * - Layer 1: Current config assets (read from active RuntimeThemeConfig)
231
- * - Layer 2: Last working asset config (in-memory, persists across config updates)
232
- * - Falls back to last complete working config if current config breaks
233
- *
234
- * This matches the ResourceLoader and ThemeService pattern where:
235
- * - User preferences/working configs are stored in memory layers
236
- * - When new config fails, the last working config is used automatically
237
- * - Handles asset removal, name changes, path changes, config resets
373
+ * Theme Storage Service
374
+ * Handles persistent theme preferences using localStorage
238
375
  */
239
- class ThemeAssetsService {
240
- /**
241
- * Signal holding current runtime configuration reference
242
- * Used to look up asset definitions for the active theme
243
- */
244
- config = signal(null);
245
- /**
246
- * Layer 1: In-memory cache of resolved assets
247
- * Maps "themeName:assetKey" to CachedAsset for fast retrieval
248
- * Cleared when setConfig() is called to force re-resolution from new config
249
- */
250
- assetCache = new Map();
251
- /**
252
- * Layer 2: Last working config storage (memory-based)
253
- * Stores the most recent RuntimeThemeConfig that successfully resolved assets
254
- * Persists across config updates as a complete fallback mechanism
255
- * Similar to ThemeService's multi-layer config persistence
256
- *
257
- * When current config fails to provide an asset:
258
- * - Falls back to the last complete working config
259
- * - Handles asset removal, name changes, path changes
260
- * - Automatically restores working state on config resets
261
- * - No individual URL tracking - entire config stored once per successful load
262
- */
263
- lastWorkingConfigLayer = null;
376
+ /**
377
+ * Service for managing theme preferences in local storage
378
+ * Provides safe access to localStorage with error handling
379
+ * Works gracefully in non-browser environments (SSR)
380
+ */
381
+ class ThemeStorageService {
264
382
  logger = inject(LoggerService);
265
- constructor() { }
266
383
  /**
267
- * Initialize service with runtime configuration
268
- * Called by ThemeService after loading configuration
269
- *
270
- * If new config successfully resolves assets, it becomes the new fallback layer.
271
- * Otherwise, previous working config persists.
272
- *
273
- * Only updates Layer 2 if:
274
- * - Config has no PARTIAL/BROKEN assets (missing variants)
275
- * - Themes can be removed entirely (that's intentional)
276
- * - But existing assets must be COMPLETE (both light and dark)
277
- *
278
- * This ensures that accidental removals of variants trigger fallback
279
- * while intentional complete removals are allowed.
280
- *
281
- * @param config - Runtime configuration containing asset definitions
384
+ * Retrieves the saved theme preference from localStorage
385
+ * Returns null if no saved preference or storage unavailable
386
+ * @returns Saved theme name or null
282
387
  */
283
- setConfig(config) {
284
- this.config.set(config);
285
- const hasPartialAssets = this.hasPartialAssets(config);
286
- const hasValid = !hasPartialAssets;
287
- this.logger.debug('setConfig called', {
288
- component: 'ThemeAssetsService',
289
- action: 'setConfig',
290
- hasPartialAssets,
291
- hasValidAssets: hasValid,
292
- themes: config?.assets ? Object.keys(config.assets) : [],
293
- hasLastWorking: !!this.lastWorkingConfigLayer,
294
- });
295
- // Only store as last working config if it has NO partial/broken assets
296
- if (hasValid) {
297
- this.logger.debug('Storing config as last working config', {
298
- component: 'ThemeAssetsService',
299
- action: 'setConfig',
300
- });
301
- this.lastWorkingConfigLayer = config;
388
+ getSavedTheme() {
389
+ try {
390
+ if (!hasLocalStorage()) {
391
+ return null;
392
+ }
393
+ const key = this.getStorageKey(THEME_STORAGE_THEME_KEY);
394
+ return localStorage.getItem(key);
302
395
  }
303
- else {
304
- this.logger.debug('Config has partial/broken assets - keeping previous last working config', {
305
- component: 'ThemeAssetsService',
306
- action: 'setConfig',
396
+ catch (error) {
397
+ this.logger.error('Failed to retrieve saved theme', error, {
398
+ component: 'ThemeStorageService',
399
+ action: 'getSavedTheme',
307
400
  });
401
+ return null;
308
402
  }
309
- this.clearCache();
310
403
  }
311
404
  /**
312
- * Internal: Check if config has any PARTIAL/BROKEN assets
313
- * Returns true if ANY asset is incomplete (missing light or dark variant)
314
- *
315
- * A partial asset is invalid:
316
- * - logo: { light: "..." } ← missing dark
317
- * - logo: { dark: "..." } ← missing light
318
- * - logo: {} ← missing both
319
- *
320
- * Complete removals are OK:
321
- * - {} ← no assets at all (intentional)
322
- * - theme: {} ← theme removed (intentional)
323
- *
324
- * @private
325
- * @param config - Config to check
405
+ * Saves the current theme preference to localStorage
406
+ * Fails silently if storage is unavailable
407
+ * @param theme - Theme name to save
408
+ */
409
+ saveTheme(theme) {
410
+ try {
411
+ if (!hasLocalStorage()) {
412
+ return;
413
+ }
414
+ const key = this.getStorageKey(THEME_STORAGE_THEME_KEY);
415
+ localStorage.setItem(key, theme);
416
+ }
417
+ catch (error) {
418
+ this.logger.error('Failed to save theme', error, {
419
+ component: 'ThemeStorageService',
420
+ action: 'saveTheme',
421
+ theme,
422
+ });
423
+ }
424
+ }
425
+ /**
426
+ * Retrieves the saved scheme preference from localStorage
427
+ * Returns null if no saved preference or storage unavailable
428
+ * @returns Saved scheme ('system', 'light', 'dark') or null
429
+ */
430
+ getSavedScheme() {
431
+ try {
432
+ if (!hasLocalStorage()) {
433
+ return null;
434
+ }
435
+ const key = this.getStorageKey(THEME_STORAGE_SCHEME_KEY);
436
+ return localStorage.getItem(key);
437
+ }
438
+ catch (error) {
439
+ this.logger.error('Failed to retrieve saved scheme', error, {
440
+ component: 'ThemeStorageService',
441
+ action: 'getSavedScheme',
442
+ });
443
+ return null;
444
+ }
445
+ }
446
+ /**
447
+ * Saves the current scheme preference to localStorage
448
+ * Fails silently if storage is unavailable
449
+ * @param scheme - Scheme to save
450
+ */
451
+ saveScheme(scheme) {
452
+ try {
453
+ if (!hasLocalStorage()) {
454
+ return;
455
+ }
456
+ const key = this.getStorageKey(THEME_STORAGE_SCHEME_KEY);
457
+ localStorage.setItem(key, scheme);
458
+ }
459
+ catch (error) {
460
+ this.logger.error('Failed to save scheme', error, {
461
+ component: 'ThemeStorageService',
462
+ action: 'saveScheme',
463
+ scheme,
464
+ });
465
+ }
466
+ }
467
+ /**
468
+ * Clears all saved theme preferences from localStorage
469
+ * Useful for resetting to defaults
470
+ */
471
+ clear() {
472
+ try {
473
+ if (!hasLocalStorage()) {
474
+ return;
475
+ }
476
+ const themeKey = this.getStorageKey(THEME_STORAGE_THEME_KEY);
477
+ const schemeKey = this.getStorageKey(THEME_STORAGE_SCHEME_KEY);
478
+ localStorage.removeItem(themeKey);
479
+ localStorage.removeItem(schemeKey);
480
+ }
481
+ catch (error) {
482
+ this.logger.error('Failed to clear storage', error, {
483
+ component: 'ThemeStorageService',
484
+ action: 'clear',
485
+ });
486
+ }
487
+ }
488
+ /**
489
+ * Constructs a namespaced storage key to avoid collisions
490
+ * @param key - The base storage key
491
+ * @returns Namespaced key (e.g., "theme:selectedTheme")
492
+ */
493
+ getStorageKey(key) {
494
+ return `${THEME_STORAGE_NAMESPACE}${key}`;
495
+ }
496
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: ThemeStorageService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
497
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: ThemeStorageService, providedIn: 'root' });
498
+ }
499
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: ThemeStorageService, decorators: [{
500
+ type: Injectable,
501
+ args: [{ providedIn: 'root' }]
502
+ }] });
503
+
504
+ /**
505
+ * Theme Assets Service
506
+ * Manages dynamic asset loading and retrieval based on selected theme and color scheme
507
+ *
508
+ * Responsibilities:
509
+ * - Retrieve assets (images, logos, illustrations) for current theme
510
+ * - Provide scheme-aware asset variants (light/dark)
511
+ * - Cache asset references with config-based resilience strategy
512
+ * - Validate asset availability and provide graceful fallback through memory layers
513
+ *
514
+ * Multi-Layer Caching Strategy (Like Theme Config Persistence):
515
+ * - Layer 1: Current config assets (read from active RuntimeThemeConfig)
516
+ * - Layer 2: Last working asset config (in-memory, persists across config updates)
517
+ * - Falls back to last complete working config if current config breaks
518
+ *
519
+ * This matches the runtime-config and ThemeService pattern where:
520
+ * - User preferences/working configs are stored in memory layers
521
+ * - When new config fails, the last working config is used automatically
522
+ * - Handles asset removal, name changes, path changes, config resets
523
+ */
524
+ class ThemeAssetsService {
525
+ /**
526
+ * Signal holding current runtime configuration reference
527
+ * Used to look up asset definitions for the active theme
528
+ */
529
+ config = signal(null);
530
+ themeConfigs = new Map();
531
+ /**
532
+ * Layer 1: In-memory cache of resolved assets
533
+ * Maps "themeName:assetKey" to CachedAsset for fast retrieval
534
+ * Cleared when setConfig() is called to force re-resolution from new config
535
+ */
536
+ assetCacheByTheme = new Map();
537
+ /**
538
+ * Layer 2: Last working config storage (memory-based)
539
+ * Stores the most recent RuntimeThemeConfig that successfully resolved assets
540
+ * Persists across config updates as a complete fallback mechanism
541
+ * Similar to ThemeService's multi-layer config persistence
542
+ *
543
+ * When current config fails to provide an asset:
544
+ * - Falls back to the last complete working config
545
+ * - Handles asset removal, name changes, path changes
546
+ * - Automatically restores working state on config resets
547
+ * - No individual URL tracking - entire config stored once per successful load
548
+ */
549
+ lastWorkingConfigLayer = null;
550
+ logger = inject(LoggerService);
551
+ constructor() { }
552
+ /**
553
+ * Initialize service with runtime configuration
554
+ * Called by ThemeService after loading configuration
555
+ *
556
+ * If new config successfully resolves assets, it becomes the new fallback layer.
557
+ * Otherwise, previous working config persists.
558
+ *
559
+ * Only updates Layer 2 if:
560
+ * - Config has no PARTIAL/BROKEN assets (missing variants)
561
+ * - Themes can be removed entirely (that's intentional)
562
+ * - But existing assets must be COMPLETE (both light and dark)
563
+ *
564
+ * This ensures that accidental removals of variants trigger fallback
565
+ * while intentional complete removals are allowed.
566
+ *
567
+ * @param config - Runtime configuration containing asset definitions
568
+ */
569
+ setConfig(config) {
570
+ this.config.set(config);
571
+ const hasPartialAssets = this.hasPartialAssets(config);
572
+ const hasValid = !hasPartialAssets;
573
+ this.logger.debug('setConfig called', {
574
+ component: 'ThemeAssetsService',
575
+ action: 'setConfig',
576
+ hasPartialAssets,
577
+ hasValidAssets: hasValid,
578
+ assets: config?.assets ? config.assets.map((asset) => asset.name) : [],
579
+ hasLastWorking: !!this.lastWorkingConfigLayer,
580
+ });
581
+ // Only store as last working config if it has NO partial/broken assets
582
+ if (hasValid) {
583
+ this.logger.debug('Storing config as last working config', {
584
+ component: 'ThemeAssetsService',
585
+ action: 'setConfig',
586
+ });
587
+ this.lastWorkingConfigLayer = config;
588
+ }
589
+ else {
590
+ this.logger.debug('Config has partial/broken assets - keeping previous last working config', {
591
+ component: 'ThemeAssetsService',
592
+ action: 'setConfig',
593
+ });
594
+ }
595
+ this.clearCache();
596
+ }
597
+ setThemeConfig(themeName, config) {
598
+ this.themeConfigs.set(themeName, config);
599
+ this.config.set(config);
600
+ this.lastWorkingConfigLayer = config;
601
+ this.clearCache(themeName);
602
+ }
603
+ /**
604
+ * Internal: Check if config has any PARTIAL/BROKEN assets
605
+ * Returns true if ANY asset is incomplete (missing light or dark variant)
606
+ *
607
+ * A partial asset is invalid:
608
+ * - { name: "logo", light: "..." } ← missing dark
609
+ * - { name: "logo", dark: "..." } ← missing light
610
+ * - { name: "logo" } ← missing both
611
+ *
612
+ * Complete removals are OK:
613
+ * - [] ← no assets at all (intentional)
614
+ * - theme: {} ← theme removed (intentional)
615
+ *
616
+ * @private
617
+ * @param config - Config to check
326
618
  * @returns True if config has partial/broken assets, false if all complete or intentionally removed
327
619
  */
328
620
  hasPartialAssets(config) {
329
621
  if (!config?.assets)
330
622
  return false;
331
- // Check if ANY theme has ANY problematic assets
332
- // Problematic = partial (missing variant) OR empty (intentionally removed)
333
- for (const themeName in config.assets) {
334
- const themeAssets = config.assets[themeName];
335
- if (this.themeHasProblematicAssets(themeAssets)) {
336
- return true; // Config has issues, don't update Layer 2
337
- }
338
- }
339
- return false; // Config is clean, can update Layer 2
623
+ return this.themeHasProblematicAssets(config.assets);
340
624
  }
341
625
  /**
342
- * Internal: Check if a theme/asset object has ANY problematic assets
626
+ * Internal: Check if a theme asset list has ANY problematic assets
343
627
  * Problematic assets are:
344
- * - Partial assets: { light: "..." } or { dark: "..." } (missing variant)
345
- * - Empty asset objects: { "logo": {} } (asset key exists but has no variants)
346
- * - Broken nested assets at any level
628
+ * - Partial assets: missing light or dark variant
629
+ * - Empty assets: no variants at all
347
630
  *
348
631
  * NOT problematic:
349
- * - Completely empty themes: {} (all assets intentionally removed - OK to accept)
350
- * - Missing themes (not in config at all)
632
+ * - Completely empty list: [] (all assets intentionally removed - OK to accept)
351
633
  *
352
634
  * @private
353
635
  * @param obj - Theme's asset object to check
354
636
  * @returns True if object has problematic assets
355
637
  */
356
- themeHasProblematicAssets(obj) {
357
- if (!obj || typeof obj !== 'object')
638
+ themeHasProblematicAssets(assets) {
639
+ if (!assets.length) {
358
640
  return false;
359
- const record = obj;
360
- const keys = Object.keys(record);
361
- // Empty theme assets {} is OK - intentional complete removal
362
- // No need to check further, this is a valid state
363
- if (keys.length === 0) {
364
- return false; // Empty theme is fine, accept config
365
- }
366
- // Theme has content - check all properties for problems
367
- for (const key of keys) {
368
- const value = record[key];
369
- // Check if this value is a partial asset (has light OR dark but not both)
370
- if (this.isPartialAsset(value)) {
371
- return true; // Partial asset found - problematic
372
- }
373
- // Check if it's an empty object (asset key exists but has no content)
374
- // Example: { "logo": {} } - the logo key exists but is empty
375
- if (typeof value === 'object' && value !== null && Object.keys(value).length === 0) {
376
- return true; // Empty asset found (key exists but broken) - problematic
377
- }
378
- // Recursively check for problematic nested assets
379
- if (this.themeHasProblematicAssets(value)) {
641
+ }
642
+ for (const asset of assets) {
643
+ if (this.isPartialAsset(asset)) {
380
644
  return true;
381
645
  }
382
646
  }
383
- return false; // No problematic assets found
647
+ return false;
384
648
  }
385
649
  /**
386
650
  * Internal: Check if object is a PARTIAL asset (incomplete)
@@ -390,15 +654,13 @@ class ThemeAssetsService {
390
654
  * @param obj - Object to check
391
655
  * @returns True if object is a partial/incomplete asset
392
656
  */
393
- isPartialAsset(obj) {
394
- if (typeof obj !== 'object' || obj === null)
395
- return false;
396
- const record = obj;
397
- const hasLight = typeof record['light'] === 'string';
398
- const hasDark = typeof record['dark'] === 'string';
399
- // Partial if it has scheme keys but not both
400
- const hasSchemeKeys = 'light' in record || 'dark' in record;
401
- return hasSchemeKeys && (!hasLight || !hasDark);
657
+ isPartialAsset(asset) {
658
+ const hasLight = typeof asset.light === 'string';
659
+ const hasDark = typeof asset.dark === 'string';
660
+ if (!hasLight && !hasDark) {
661
+ return true;
662
+ }
663
+ return !hasLight || !hasDark;
402
664
  }
403
665
  /**
404
666
  * Get asset URL for the specified scheme
@@ -435,17 +697,24 @@ class ThemeAssetsService {
435
697
  * // Returns: null
436
698
  */
437
699
  getAssetUrl(themeName, assetKey, scheme) {
700
+ const cacheKey = `${themeName}:${assetKey}`;
701
+ const themeCache = this.assetCacheByTheme.get(themeName);
702
+ const cached = themeCache?.get(cacheKey);
703
+ if (cached) {
704
+ return scheme === 'light' ? cached.light : cached.dark;
705
+ }
438
706
  // Layer 1: Try to resolve from current config
439
- const url = this.resolveAssetUrl(themeName, assetKey, scheme, this.config());
707
+ const configToUse = this.themeConfigs.get(themeName) ?? this.config();
708
+ const url = this.resolveAssetUrl(themeName, assetKey, scheme, configToUse);
440
709
  if (url) {
441
710
  this.logger.debug('Asset resolved from current config', {
442
711
  component: 'ThemeAssetsService',
443
712
  action: 'getAssetUrl',
444
- themeName,
445
713
  assetKey,
446
714
  scheme,
447
715
  url,
448
716
  });
717
+ this.cacheAsset(themeName, assetKey, configToUse);
449
718
  return url;
450
719
  }
451
720
  // Layer 2: Try to resolve from last working config
@@ -456,11 +725,11 @@ class ThemeAssetsService {
456
725
  component: 'ThemeAssetsService',
457
726
  action: 'getAssetUrl',
458
727
  fallback: true,
459
- themeName,
460
728
  assetKey,
461
729
  scheme,
462
730
  url: lastWorkingUrl,
463
731
  });
732
+ this.cacheAsset(themeName, assetKey, this.lastWorkingConfigLayer);
464
733
  return lastWorkingUrl;
465
734
  }
466
735
  }
@@ -468,7 +737,6 @@ class ThemeAssetsService {
468
737
  this.logger.debug('Asset not found in any layer', {
469
738
  component: 'ThemeAssetsService',
470
739
  action: 'getAssetUrl',
471
- themeName,
472
740
  assetKey,
473
741
  scheme,
474
742
  hasLastWorking: !!this.lastWorkingConfigLayer,
@@ -492,22 +760,13 @@ class ThemeAssetsService {
492
760
  * @returns URL if found and complete, null otherwise
493
761
  */
494
762
  resolveAssetUrl(themeName, assetKey, scheme, configToUse) {
495
- if (!configToUse?.assets?.[themeName])
763
+ if (!configToUse?.assets)
496
764
  return null;
497
- const themeAssets = configToUse.assets[themeName];
498
- const parts = assetKey.split('.');
499
- // Navigate nested structure
500
- let current = themeAssets;
501
- for (const part of parts) {
502
- if (!current || typeof current !== 'object')
503
- return null;
504
- current = current[part];
505
- }
506
- // Check if it's a valid asset with the requested scheme
507
- if (!this.isThemeAsset(current))
765
+ if (configToUse.meta?.name && configToUse.meta.name !== themeName)
766
+ return null;
767
+ const asset = this.findAsset(configToUse.assets, assetKey);
768
+ if (!asset || !this.isThemeAsset(asset))
508
769
  return null;
509
- // Asset must be complete (have both variants) - return requested variant
510
- const asset = current;
511
770
  const url = scheme === 'light' ? asset.light : asset.dark;
512
771
  // Return null if variant is missing (indicates incomplete asset)
513
772
  return url || null;
@@ -526,8 +785,9 @@ class ThemeAssetsService {
526
785
  */
527
786
  getAsset(themeName, assetKey) {
528
787
  // Try current config first
529
- let light = this.resolveAssetUrl(themeName, assetKey, 'light', this.config());
530
- let dark = this.resolveAssetUrl(themeName, assetKey, 'dark', this.config());
788
+ const configToUse = this.themeConfigs.get(themeName) ?? this.config();
789
+ let light = this.resolveAssetUrl(themeName, assetKey, 'light', configToUse);
790
+ let dark = this.resolveAssetUrl(themeName, assetKey, 'dark', configToUse);
531
791
  // If not available in current config, try last working config
532
792
  if ((!light || !dark) && this.lastWorkingConfigLayer) {
533
793
  if (!light)
@@ -537,6 +797,7 @@ class ThemeAssetsService {
537
797
  }
538
798
  // Return asset if at least one variant found
539
799
  if (light || dark) {
800
+ this.cacheAsset(themeName, assetKey, configToUse ?? this.lastWorkingConfigLayer);
540
801
  return { light: light || undefined, dark: dark || undefined };
541
802
  }
542
803
  return null;
@@ -555,7 +816,8 @@ class ThemeAssetsService {
555
816
  */
556
817
  hasAsset(themeName, assetKey) {
557
818
  // Check if asset exists in current config
558
- if (this.resolveAssetUrl(themeName, assetKey, 'light', this.config()) || this.resolveAssetUrl(themeName, assetKey, 'dark', this.config())) {
819
+ const configToUse = this.themeConfigs.get(themeName) ?? this.config();
820
+ if (this.resolveAssetUrl(themeName, assetKey, 'light', configToUse) || this.resolveAssetUrl(themeName, assetKey, 'dark', configToUse)) {
559
821
  return true;
560
822
  }
561
823
  // Check if asset exists in last working config
@@ -575,10 +837,12 @@ class ThemeAssetsService {
575
837
  * @returns All assets for the theme, or null if theme has no assets
576
838
  */
577
839
  getThemeAssets(themeName) {
578
- const cfg = this.config();
579
- if (!cfg?.assets?.[themeName])
840
+ const cfg = this.themeConfigs.get(themeName) ?? this.config();
841
+ if (!cfg?.assets)
580
842
  return null;
581
- return cfg.assets[themeName];
843
+ if (cfg.meta?.name && cfg.meta.name !== themeName)
844
+ return null;
845
+ return cfg.assets;
582
846
  }
583
847
  /**
584
848
  * Manually clear the asset cache
@@ -598,8 +862,27 @@ class ThemeAssetsService {
598
862
  * assetsService.clearCache();
599
863
  * assetsService.setConfig(currentConfig);
600
864
  */
601
- clearCache() {
602
- this.assetCache.clear();
865
+ clearCache(themeName) {
866
+ if (themeName) {
867
+ this.assetCacheByTheme.delete(themeName);
868
+ return;
869
+ }
870
+ this.assetCacheByTheme.clear();
871
+ }
872
+ async prefetchAssets(themeName) {
873
+ const cfg = this.themeConfigs.get(themeName) ?? this.config();
874
+ if (!cfg?.assets) {
875
+ return;
876
+ }
877
+ if (cfg.meta?.name && cfg.meta.name !== themeName) {
878
+ return;
879
+ }
880
+ const urls = new Set();
881
+ this.collectAssetUrls(cfg.assets, urls);
882
+ await Promise.allSettled([...urls].map((url) => fetch(url, {
883
+ method: 'GET',
884
+ cache: 'no-store',
885
+ }).catch(() => undefined)));
603
886
  }
604
887
  /**
605
888
  * Internal: Type guard to validate ThemeAsset structure
@@ -625,6 +908,40 @@ class ThemeAssetsService {
625
908
  // Valid only if BOTH variants are present
626
909
  return hasLight && hasDark;
627
910
  }
911
+ collectAssetUrls(assets, urls) {
912
+ for (const asset of assets) {
913
+ if (!this.isThemeAsset(asset)) {
914
+ continue;
915
+ }
916
+ if (asset.light)
917
+ urls.add(asset.light);
918
+ if (asset.dark)
919
+ urls.add(asset.dark);
920
+ }
921
+ }
922
+ findAsset(assets, assetKey) {
923
+ return assets.find((asset) => asset.name === assetKey) ?? null;
924
+ }
925
+ cacheAsset(themeName, assetKey, config) {
926
+ if (!config) {
927
+ return;
928
+ }
929
+ const light = this.resolveAssetUrl(themeName, assetKey, 'light', config);
930
+ const dark = this.resolveAssetUrl(themeName, assetKey, 'dark', config);
931
+ if (!light && !dark) {
932
+ return;
933
+ }
934
+ const cacheKey = `${themeName}:${assetKey}`;
935
+ if (!this.assetCacheByTheme.has(themeName)) {
936
+ this.assetCacheByTheme.set(themeName, new Map());
937
+ }
938
+ this.assetCacheByTheme.get(themeName)?.set(cacheKey, {
939
+ themeName,
940
+ assetKey,
941
+ light: light ?? null,
942
+ dark: dark ?? null,
943
+ });
944
+ }
628
945
  static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: ThemeAssetsService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
629
946
  static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: ThemeAssetsService, providedIn: 'root' });
630
947
  }
@@ -685,6 +1002,18 @@ class ThemeDomService {
685
1002
  this.appendStyleToHead(styleContent);
686
1003
  }
687
1004
  }
1005
+ /**
1006
+ * Injects CSS variables for a single theme only
1007
+ * @param themeName - Theme key
1008
+ * @param variants - Theme variants to inject
1009
+ */
1010
+ injectSingleThemeStyles(themeName, variants) {
1011
+ const styleBlocks = this.buildThemeVariantStyles(themeName, variants);
1012
+ const styleContent = styleBlocks.filter((content) => content.length > 0).join('\n\n');
1013
+ if (styleContent) {
1014
+ this.replaceThemeStyle(themeName, styleContent);
1015
+ }
1016
+ }
688
1017
  /**
689
1018
  * Sets the active theme on the document body
690
1019
  * Uses data-theme attribute for CSS theme targeting
@@ -764,7 +1093,8 @@ class ThemeDomService {
764
1093
  */
765
1094
  buildThemeVariantRule(themeName, scheme, variables) {
766
1095
  const selector = `[${THEME_ATTRIBUTE_NAME}="${themeName}${THEME_SCHEME_SEPARATOR}${scheme}"]`;
767
- const declarations = Object.entries(variables)
1096
+ const flattened = this.flattenVariables(variables);
1097
+ const declarations = Object.entries(flattened)
768
1098
  .map(([key, value]) => `\t${key}: ${value};`)
769
1099
  .join('\n');
770
1100
  return `${selector} {
@@ -781,6 +1111,26 @@ ${declarations}
781
1111
  style.textContent = content;
782
1112
  this.renderer.appendChild(this.document.head, style);
783
1113
  }
1114
+ flattenVariables(variables) {
1115
+ return {
1116
+ ...variables.colors,
1117
+ ...variables.radius,
1118
+ ...variables.sizes,
1119
+ ...variables.effects,
1120
+ ...variables.others,
1121
+ };
1122
+ }
1123
+ replaceThemeStyle(themeName, content) {
1124
+ const existing = this.document.head.querySelector(`style[data-theme-style="${themeName}"]`);
1125
+ if (existing) {
1126
+ existing.textContent = content;
1127
+ return;
1128
+ }
1129
+ const style = this.renderer.createElement('style');
1130
+ style.textContent = content;
1131
+ style.setAttribute('data-theme-style', themeName);
1132
+ this.renderer.appendChild(this.document.head, style);
1133
+ }
784
1134
  static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: ThemeDomService, deps: [{ token: i0.RendererFactory2 }, { token: DOCUMENT }], target: i0.ɵɵFactoryTarget.Injectable });
785
1135
  static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: ThemeDomService, providedIn: 'root' });
786
1136
  }
@@ -792,151 +1142,6 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.0", ngImpor
792
1142
  args: [DOCUMENT]
793
1143
  }] }] });
794
1144
 
795
- /**
796
- * Theme Utility Functions
797
- * Pure, side-effect-free utilities for theme logic
798
- */
799
- /**
800
- * Validates that a given value is a valid theme scheme
801
- * @param value - The value to validate
802
- * @returns True if the value is a valid scheme ('system', 'light', or 'dark')
803
- */
804
- function isValidScheme(value) {
805
- return typeof value === 'string' && VALID_SCHEMES.includes(value);
806
- }
807
- /**
808
- * Builds the final theme identifier by combining theme name and scheme
809
- * @param themeName - The name of the theme
810
- * @param scheme - The scheme variant (light or dark)
811
- * @returns Combined identifier (e.g., "sixbell_telco__light")
812
- */
813
- function buildThemeIdentifier(themeName, scheme) {
814
- return `${themeName}__${scheme}`;
815
- }
816
- /**
817
- * Extracts theme name and scheme from a combined identifier
818
- * @param identifier - The combined identifier (e.g., "sixbell_telco__light")
819
- * @returns Object with extracted themeName and scheme
820
- */
821
- function parseThemeIdentifier(identifier) {
822
- const [themeName, scheme] = identifier.split('__');
823
- return { themeName, scheme };
824
- }
825
- /**
826
- * Builds the list of available themes from configuration
827
- * Starts with default base theme, adds additional themes, and filters exclusions
828
- * Removes duplicates and returns sorted list
829
- * @param additionalThemes - Additional themes to include
830
- * @param excludeThemes - Themes to exclude
831
- * @returns Deduplicated list of available themes
832
- */
833
- function buildAvailableThemes(additionalThemes, excludeThemes) {
834
- // Start with base theme
835
- let themes = [DEFAULT_BASE_THEME];
836
- // Add additional themes
837
- if (additionalThemes && additionalThemes.length > 0) {
838
- themes = [DEFAULT_BASE_THEME, ...additionalThemes];
839
- }
840
- // Filter exclusions
841
- if (excludeThemes && excludeThemes.length > 0) {
842
- themes = themes.filter((theme) => !excludeThemes.includes(theme));
843
- }
844
- // Remove duplicates and maintain consistency
845
- return [...new Set(themes)];
846
- }
847
- /**
848
- * Determines the effective default theme from configuration
849
- * Ensures the default theme is in the available themes list
850
- * Falls back to first available theme if default is not available
851
- * @param defaultTheme - Configured default theme
852
- * @param availableThemes - List of available themes
853
- * @returns The effective default theme to use
854
- */
855
- function resolveDefaultTheme(defaultTheme, availableThemes) {
856
- // Use provided default if valid
857
- if (defaultTheme && availableThemes.includes(defaultTheme)) {
858
- return defaultTheme;
859
- }
860
- // Check if base theme is available
861
- if (availableThemes.includes(DEFAULT_BASE_THEME)) {
862
- return DEFAULT_BASE_THEME;
863
- }
864
- // Fallback to first available
865
- return availableThemes[0] || DEFAULT_BASE_THEME;
866
- }
867
- /**
868
- * Validates that a given theme exists in the available themes
869
- * @param theme - Theme name to validate
870
- * @param availableThemes - List of available themes
871
- * @returns True if theme is available
872
- */
873
- function isThemeAvailable(theme, availableThemes) {
874
- return availableThemes.includes(theme);
875
- }
876
- /**
877
- * Validates the configuration and logs warnings for invalid states
878
- * Returns true if configuration is valid for use
879
- * @param config - Configuration to validate
880
- * @param configName - Name of config for logging purposes
881
- * @returns True if configuration is valid
882
- */
883
- function validateThemeConfig(config, configName = 'ThemeConfig') {
884
- const errors = [];
885
- if (!config.availableThemes || config.availableThemes.length === 0) {
886
- errors.push('availableThemes must be a non-empty array');
887
- }
888
- if (!config.defaultTheme) {
889
- errors.push('defaultTheme must be defined');
890
- }
891
- if (config.defaultTheme && !config.availableThemes.includes(config.defaultTheme)) {
892
- errors.push(`defaultTheme '${config.defaultTheme}' not in availableThemes`);
893
- }
894
- if (errors.length > 0) {
895
- console.error(`${configName} validation failed:`, errors.join(', '));
896
- return false;
897
- }
898
- return true;
899
- }
900
- /**
901
- * Formats a theme name for display to users
902
- * Converts snake_case to Title Case
903
- * @param theme - Theme name to format
904
- * @returns Formatted theme name
905
- */
906
- function formatThemeName(theme) {
907
- return theme.replace(/_/g, ' ').replace(/\b\w/g, (l) => l.toUpperCase());
908
- }
909
- /**
910
- * Formats a scheme name for display to users
911
- * Capitalizes first letter
912
- * @param scheme - Scheme name to format
913
- * @returns Formatted scheme name
914
- */
915
- function formatSchemeName(scheme) {
916
- return scheme.charAt(0).toUpperCase() + scheme.slice(1);
917
- }
918
- /**
919
- * Checks if the browser supports the matchMedia API
920
- * Safe to call in non-browser environments
921
- * @returns True if matchMedia is available
922
- */
923
- function supportsMediaQuery() {
924
- return typeof window !== 'undefined' && typeof window.matchMedia === 'function';
925
- }
926
- /**
927
- * Checks if localStorage is available in the current environment
928
- * Safe to call in non-browser environments
929
- * @returns True if localStorage is accessible
930
- */
931
- function hasLocalStorage() {
932
- try {
933
- return typeof window !== 'undefined' && typeof localStorage !== 'undefined' && localStorage !== null;
934
- }
935
- catch {
936
- return false;
937
- }
938
- }
939
-
940
1145
  /**
941
1146
  * Theme Scheme Resolver Service
942
1147
  * Handles scheme detection and resolution (system -> light/dark)
@@ -950,227 +1155,96 @@ class ThemeSchemeService {
950
1155
  /**
951
1156
  * Media query list for detecting dark mode preference
952
1157
  * Cached to avoid repeated queries
953
- */
954
- darkModeMediaQuery = null;
955
- /**
956
- * Resolves a theme scheme to its actual light/dark value
957
- * If scheme is 'system', detects the OS preference
958
- * If scheme is already 'light' or 'dark', returns it as-is
959
- * @param scheme - The scheme to resolve
960
- * @returns Resolved scheme ('light' or 'dark')
961
- */
962
- resolveScheme(scheme) {
963
- if (scheme === 'system') {
964
- return this.detectSystemScheme();
965
- }
966
- return scheme;
967
- }
968
- /**
969
- * Detects the system's preferred color scheme
970
- * Uses CSS media query (prefers-color-scheme: dark)
971
- * Safely handles environments where matchMedia is not available
972
- * @returns 'dark' if system prefers dark, 'light' otherwise
973
- */
974
- detectSystemScheme() {
975
- if (!supportsMediaQuery()) {
976
- // Fallback to light in non-browser environments
977
- return 'light';
978
- }
979
- // Use cached media query list if available
980
- if (!this.darkModeMediaQuery) {
981
- this.darkModeMediaQuery = this.createMediaQuery();
982
- }
983
- return this.darkModeMediaQuery.matches ? 'dark' : 'light';
984
- }
985
- /**
986
- * Listens for changes in system color scheme preference
987
- * Allows components to react to OS theme changes
988
- * @param listener - Callback function when scheme changes
989
- * @returns Unsubscribe function to remove listener
990
- */
991
- listenToSystemSchemeChanges(listener) {
992
- if (!supportsMediaQuery()) {
993
- // Return no-op unsubscribe function if matchMedia not available
994
- return () => { };
995
- }
996
- const mediaQuery = this.createMediaQuery();
997
- const handleChange = (e) => {
998
- listener(e.matches ? 'dark' : 'light');
999
- };
1000
- // Use addEventListener for modern browsers
1001
- if (mediaQuery.addEventListener) {
1002
- mediaQuery.addEventListener('change', handleChange);
1003
- return () => mediaQuery.removeEventListener('change', handleChange);
1004
- }
1005
- // Fallback for older browsers using addListener (deprecated but supported)
1006
- const legacyMediaQuery = mediaQuery;
1007
- legacyMediaQuery.addListener?.(handleChange);
1008
- return () => legacyMediaQuery.removeListener?.(handleChange);
1009
- }
1010
- /**
1011
- * Creates a media query for detecting dark mode
1012
- * Extracted method to make testing easier
1013
- * @returns MediaQueryList for dark mode preference
1014
- */
1015
- createMediaQuery() {
1016
- return window.matchMedia(DARK_MODE_MEDIA_QUERY);
1017
- }
1018
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: ThemeSchemeService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
1019
- static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: ThemeSchemeService, providedIn: 'root' });
1020
- }
1021
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: ThemeSchemeService, decorators: [{
1022
- type: Injectable,
1023
- args: [{ providedIn: 'root' }]
1024
- }] });
1025
-
1026
- /**
1027
- * Theme Storage Service
1028
- * Handles persistent theme preferences using localStorage
1029
- */
1030
- /**
1031
- * Service for managing theme preferences in local storage
1032
- * Provides safe access to localStorage with error handling
1033
- * Works gracefully in non-browser environments (SSR)
1034
- */
1035
- class ThemeStorageService {
1036
- logger = inject(LoggerService);
1037
- /**
1038
- * Retrieves the saved theme preference from localStorage
1039
- * Returns null if no saved preference or storage unavailable
1040
- * @returns Saved theme name or null
1041
- */
1042
- getSavedTheme() {
1043
- try {
1044
- if (!hasLocalStorage()) {
1045
- return null;
1046
- }
1047
- const key = this.getStorageKey(THEME_STORAGE_THEME_KEY);
1048
- return localStorage.getItem(key);
1049
- }
1050
- catch (error) {
1051
- this.logger.error('Failed to retrieve saved theme', error, {
1052
- component: 'ThemeStorageService',
1053
- action: 'getSavedTheme',
1054
- });
1055
- return null;
1056
- }
1057
- }
1058
- /**
1059
- * Saves the current theme preference to localStorage
1060
- * Fails silently if storage is unavailable
1061
- * @param theme - Theme name to save
1062
- */
1063
- saveTheme(theme) {
1064
- try {
1065
- if (!hasLocalStorage()) {
1066
- return;
1067
- }
1068
- const key = this.getStorageKey(THEME_STORAGE_THEME_KEY);
1069
- localStorage.setItem(key, theme);
1070
- }
1071
- catch (error) {
1072
- this.logger.error('Failed to save theme', error, {
1073
- component: 'ThemeStorageService',
1074
- action: 'saveTheme',
1075
- theme,
1076
- });
1077
- }
1078
- }
1079
- /**
1080
- * Retrieves the saved scheme preference from localStorage
1081
- * Returns null if no saved preference or storage unavailable
1082
- * @returns Saved scheme ('system', 'light', 'dark') or null
1083
- */
1084
- getSavedScheme() {
1085
- try {
1086
- if (!hasLocalStorage()) {
1087
- return null;
1088
- }
1089
- const key = this.getStorageKey(THEME_STORAGE_SCHEME_KEY);
1090
- return localStorage.getItem(key);
1091
- }
1092
- catch (error) {
1093
- this.logger.error('Failed to retrieve saved scheme', error, {
1094
- component: 'ThemeStorageService',
1095
- action: 'getSavedScheme',
1096
- });
1097
- return null;
1158
+ */
1159
+ darkModeMediaQuery = null;
1160
+ /**
1161
+ * Resolves a theme scheme to its actual light/dark value
1162
+ * If scheme is 'system', detects the OS preference
1163
+ * If scheme is already 'light' or 'dark', returns it as-is
1164
+ * @param scheme - The scheme to resolve
1165
+ * @returns Resolved scheme ('light' or 'dark')
1166
+ */
1167
+ resolveScheme(scheme) {
1168
+ if (scheme === 'system') {
1169
+ return this.detectSystemScheme();
1098
1170
  }
1171
+ return scheme;
1099
1172
  }
1100
1173
  /**
1101
- * Saves the current scheme preference to localStorage
1102
- * Fails silently if storage is unavailable
1103
- * @param scheme - Scheme to save
1174
+ * Detects the system's preferred color scheme
1175
+ * Uses CSS media query (prefers-color-scheme: dark)
1176
+ * Safely handles environments where matchMedia is not available
1177
+ * @returns 'dark' if system prefers dark, 'light' otherwise
1104
1178
  */
1105
- saveScheme(scheme) {
1106
- try {
1107
- if (!hasLocalStorage()) {
1108
- return;
1109
- }
1110
- const key = this.getStorageKey(THEME_STORAGE_SCHEME_KEY);
1111
- localStorage.setItem(key, scheme);
1179
+ detectSystemScheme() {
1180
+ if (!supportsMediaQuery()) {
1181
+ // Fallback to light in non-browser environments
1182
+ return 'light';
1112
1183
  }
1113
- catch (error) {
1114
- this.logger.error('Failed to save scheme', error, {
1115
- component: 'ThemeStorageService',
1116
- action: 'saveScheme',
1117
- scheme,
1118
- });
1184
+ // Use cached media query list if available
1185
+ if (!this.darkModeMediaQuery) {
1186
+ this.darkModeMediaQuery = this.createMediaQuery();
1119
1187
  }
1188
+ return this.darkModeMediaQuery.matches ? 'dark' : 'light';
1120
1189
  }
1121
1190
  /**
1122
- * Clears all saved theme preferences from localStorage
1123
- * Useful for resetting to defaults
1191
+ * Listens for changes in system color scheme preference
1192
+ * Allows components to react to OS theme changes
1193
+ * @param listener - Callback function when scheme changes
1194
+ * @returns Unsubscribe function to remove listener
1124
1195
  */
1125
- clear() {
1126
- try {
1127
- if (!hasLocalStorage()) {
1128
- return;
1129
- }
1130
- const themeKey = this.getStorageKey(THEME_STORAGE_THEME_KEY);
1131
- const schemeKey = this.getStorageKey(THEME_STORAGE_SCHEME_KEY);
1132
- localStorage.removeItem(themeKey);
1133
- localStorage.removeItem(schemeKey);
1196
+ listenToSystemSchemeChanges(listener) {
1197
+ if (!supportsMediaQuery()) {
1198
+ // Return no-op unsubscribe function if matchMedia not available
1199
+ return () => { };
1134
1200
  }
1135
- catch (error) {
1136
- this.logger.error('Failed to clear storage', error, {
1137
- component: 'ThemeStorageService',
1138
- action: 'clear',
1139
- });
1201
+ const mediaQuery = this.createMediaQuery();
1202
+ const handleChange = (e) => {
1203
+ listener(e.matches ? 'dark' : 'light');
1204
+ };
1205
+ // Use addEventListener for modern browsers
1206
+ if (mediaQuery.addEventListener) {
1207
+ mediaQuery.addEventListener('change', handleChange);
1208
+ return () => mediaQuery.removeEventListener('change', handleChange);
1140
1209
  }
1210
+ // Fallback for older browsers using addListener (deprecated but supported)
1211
+ const legacyMediaQuery = mediaQuery;
1212
+ legacyMediaQuery.addListener?.(handleChange);
1213
+ return () => legacyMediaQuery.removeListener?.(handleChange);
1141
1214
  }
1142
1215
  /**
1143
- * Constructs a namespaced storage key to avoid collisions
1144
- * @param key - The base storage key
1145
- * @returns Namespaced key (e.g., "theme:selectedTheme")
1216
+ * Creates a media query for detecting dark mode
1217
+ * Extracted method to make testing easier
1218
+ * @returns MediaQueryList for dark mode preference
1146
1219
  */
1147
- getStorageKey(key) {
1148
- return `${THEME_STORAGE_NAMESPACE}${key}`;
1220
+ createMediaQuery() {
1221
+ return window.matchMedia(DARK_MODE_MEDIA_QUERY);
1149
1222
  }
1150
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: ThemeStorageService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
1151
- static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: ThemeStorageService, providedIn: 'root' });
1223
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: ThemeSchemeService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
1224
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: ThemeSchemeService, providedIn: 'root' });
1152
1225
  }
1153
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: ThemeStorageService, decorators: [{
1226
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: ThemeSchemeService, decorators: [{
1154
1227
  type: Injectable,
1155
1228
  args: [{ providedIn: 'root' }]
1156
1229
  }] });
1157
1230
 
1158
1231
  class ThemeService {
1159
- themeConfig;
1160
- runtimeThemeConfig;
1161
1232
  translationService = inject(TranslationService);
1162
1233
  domService = inject(ThemeDomService);
1163
1234
  storageService = inject(ThemeStorageService);
1164
1235
  schemeResolver = inject(ThemeSchemeService);
1165
1236
  assetsService = inject(ThemeAssetsService);
1166
- router = inject(Router);
1167
1237
  logger = inject(LoggerService);
1168
- runtimeConfigPath;
1169
- runtimeLoader;
1170
- runtimeLoaderOptions;
1171
- navigationSubscription;
1172
- skipFirstNavigation = true;
1173
1238
  isUsingFallbackConfig = false;
1239
+ runtimeHash = null;
1240
+ runtimeLoader;
1241
+ runtimeThemes = new Map();
1242
+ runtimeEventHashes = new Map();
1243
+ pendingUpdatedThemes = new Set();
1244
+ appliedThemeNames = new Set();
1245
+ refreshHandler;
1246
+ updateAvailable = signal(false);
1247
+ lastRefreshFailed = signal(false);
1174
1248
  config = {
1175
1249
  availableThemes: [DEFAULT_BASE_THEME],
1176
1250
  defaultTheme: DEFAULT_BASE_THEME,
@@ -1188,97 +1262,41 @@ class ThemeService {
1188
1262
  const scheme = this.resolvedScheme();
1189
1263
  return buildThemeIdentifier(theme, scheme);
1190
1264
  });
1191
- constructor(themeConfig, runtimeThemeConfig) {
1192
- this.themeConfig = themeConfig;
1193
- this.runtimeThemeConfig = runtimeThemeConfig;
1194
- if (themeConfig) {
1195
- this.configure(themeConfig);
1196
- }
1197
- else {
1198
- // Don't call initializeFromStorage here - the runtime config might not be loaded yet
1199
- // If we restore from storage now and the theme isn't available, we'll save the wrong value back
1200
- // The runtime provider will call configureRuntime() which will properly restore from storage
1201
- }
1202
- }
1203
- configure(config = {}) {
1204
- const availableThemes = buildAvailableThemes(config.additionalThemes, config.excludeThemes);
1205
- const defaultTheme = resolveDefaultTheme(config.defaultTheme, availableThemes);
1206
- this.config = {
1207
- availableThemes,
1208
- defaultTheme,
1209
- defaultScheme: config.defaultScheme || DEFAULT_SCHEME,
1210
- };
1211
- validateThemeConfig(this.config, 'ThemeService.configure');
1212
- this.selectedTheme.set(this.config.defaultTheme);
1213
- this.selectedScheme.set(this.config.defaultScheme);
1214
- this.initializeFromStorage();
1215
- this.applyTheme();
1216
- }
1217
- configureRuntime(config) {
1218
- // Note: isUsingFallbackConfig is set via configureRuntimeWithSource() or left from previous call
1219
- // This keeps configureRuntime compatible with existing code while allowing precise tracking
1220
- if (config.fonts && config.fonts.length > 0) {
1221
- this.domService.injectFonts(config.fonts);
1222
- }
1223
- if (config.globalVariables) {
1224
- this.domService.injectGlobalVariables(config.globalVariables);
1225
- }
1226
- if (config.themes) {
1227
- this.domService.injectThemeStyles(config.themes);
1228
- }
1229
- // Initialize assets service with configuration
1230
- this.assetsService.setConfig(config);
1231
- if (!config.themes || !Object.keys(config.themes).length) {
1265
+ constructor() { }
1266
+ async configureRuntime(config, themeName, options) {
1267
+ if (!config.themes) {
1232
1268
  this.logger.error('Invalid runtime config - no themes defined', undefined, {
1233
1269
  component: 'ThemeService',
1234
1270
  action: 'configureRuntime',
1235
1271
  });
1236
1272
  return;
1237
1273
  }
1238
- // Auto-derive availableThemes from themes object keys, apply exclusions
1239
- const themesFromConfig = Object.keys(config.themes);
1240
- const availableThemes = buildAvailableThemes(themesFromConfig, config.excludeThemes);
1241
- if (!availableThemes.length) {
1242
- this.logger.error('No themes available after applying exclusions', undefined, {
1243
- component: 'ThemeService',
1244
- action: 'configureRuntime',
1245
- });
1246
- return;
1274
+ if (config.fonts && config.fonts.length > 0) {
1275
+ this.domService.injectFonts(config.fonts);
1276
+ if (options?.blocking) {
1277
+ await this.waitForFonts();
1278
+ }
1247
1279
  }
1248
- // Use provided defaultTheme or fallback to first available theme
1249
- const defaultTheme = config.defaultTheme ? resolveDefaultTheme(config.defaultTheme, availableThemes) : availableThemes[0];
1250
- this.config = {
1251
- availableThemes,
1252
- defaultTheme,
1253
- defaultScheme: config.defaultScheme || DEFAULT_SCHEME,
1254
- };
1255
- validateThemeConfig(this.config, 'ThemeService.configureRuntime');
1256
- // Set defaults from config
1280
+ this.assetsService.setThemeConfig(themeName, config);
1281
+ const themeVariants = config.themes;
1282
+ this.runtimeThemes.set(themeName, themeVariants);
1283
+ this.domService.injectSingleThemeStyles(themeName, themeVariants);
1284
+ this.appliedThemeNames.add(themeName);
1285
+ if (options?.blocking) {
1286
+ await this.assetsService.prefetchAssets(themeName);
1287
+ }
1288
+ else {
1289
+ void this.assetsService.prefetchAssets(themeName);
1290
+ }
1291
+ }
1292
+ applyRuntimeConfig(config, source) {
1293
+ this.isUsingFallbackConfig = source === 'fallback';
1294
+ this.config = config;
1295
+ validateThemeConfig(this.config, 'ThemeService.applyRuntimeConfig');
1257
1296
  this.selectedTheme.set(this.config.defaultTheme);
1258
1297
  this.selectedScheme.set(this.config.defaultScheme);
1259
- // Always restore user's saved settings (overrides defaults if they exist)
1260
1298
  this.initializeFromStorage();
1261
1299
  this.applyTheme();
1262
- // Now that initialization is complete, set up the router subscription for fresh on navigation
1263
- // This ensures the initial navigation event doesn't trigger a reload
1264
- const freshOnNavigation = this.runtimeLoaderOptions?.freshOnNavigation ?? false;
1265
- if (freshOnNavigation && !this.navigationSubscription) {
1266
- this.navigationSubscription = this.router.events.pipe(filter((event) => event instanceof NavigationEnd)).subscribe(() => {
1267
- // Skip the first navigation event (happens during app bootstrap)
1268
- if (this.skipFirstNavigation) {
1269
- this.skipFirstNavigation = false;
1270
- return;
1271
- }
1272
- this.reloadRuntimeConfig().catch((error) => {
1273
- if (this.runtimeLoaderOptions?.logErrors !== false) {
1274
- this.logger.error('Error reloading runtime config on navigation', error, {
1275
- component: 'ThemeService',
1276
- action: 'configureRuntime.navigationSubscription',
1277
- });
1278
- }
1279
- });
1280
- });
1281
- }
1282
1300
  }
1283
1301
  setTheme(theme) {
1284
1302
  if (isThemeAvailable(theme, this.config.availableThemes)) {
@@ -1338,6 +1356,7 @@ class ThemeService {
1338
1356
  }
1339
1357
  initializeFromStorage() {
1340
1358
  const savedTheme = this.storageService.getSavedTheme();
1359
+ let skipSchemeRestore = false;
1341
1360
  this.logger.debug('initializeFromStorage - savedTheme', {
1342
1361
  component: 'ThemeService',
1343
1362
  action: 'initializeFromStorage',
@@ -1377,7 +1396,10 @@ class ThemeService {
1377
1396
  savedTheme,
1378
1397
  defaultTheme: this.config.defaultTheme,
1379
1398
  });
1399
+ this.storageService.clear();
1400
+ skipSchemeRestore = true;
1380
1401
  this.selectedTheme.set(this.config.defaultTheme);
1402
+ this.selectedScheme.set(DEFAULT_SCHEME);
1381
1403
  }
1382
1404
  }
1383
1405
  const savedScheme = this.storageService.getSavedScheme();
@@ -1386,7 +1408,7 @@ class ThemeService {
1386
1408
  action: 'initializeFromStorage',
1387
1409
  savedScheme,
1388
1410
  });
1389
- if (savedScheme && isValidScheme(savedScheme)) {
1411
+ if (savedScheme && isValidScheme(savedScheme) && !skipSchemeRestore) {
1390
1412
  this.logger.debug('Restoring saved scheme', {
1391
1413
  component: 'ThemeService',
1392
1414
  action: 'initializeFromStorage',
@@ -1394,147 +1416,462 @@ class ThemeService {
1394
1416
  });
1395
1417
  this.selectedScheme.set(savedScheme);
1396
1418
  }
1419
+ else if (savedScheme && !this.isUsingFallbackConfig) {
1420
+ this.storageService.clear();
1421
+ }
1397
1422
  }
1398
1423
  applyTheme() {
1399
1424
  const themeIdentifier = this.finalTheme();
1400
1425
  this.domService.setActiveTheme(themeIdentifier);
1401
1426
  this.storageService.saveTheme(this.selectedTheme());
1402
1427
  this.storageService.saveScheme(this.selectedScheme());
1428
+ const selectedTheme = this.selectedTheme();
1429
+ if (!this.appliedThemeNames.has(selectedTheme)) {
1430
+ const variants = this.runtimeThemes.get(selectedTheme);
1431
+ if (variants) {
1432
+ this.domService.injectSingleThemeStyles(selectedTheme, variants);
1433
+ this.appliedThemeNames.add(selectedTheme);
1434
+ }
1435
+ }
1403
1436
  }
1404
1437
  /**
1405
1438
  * Internal method to set runtime loader and enable navigation-based reloading.
1406
1439
  * Called by provideRuntimeTheme.
1407
1440
  * @internal
1408
1441
  */
1409
- setRuntimeLoader(configPath, loader, loaderOptions) {
1410
- this.runtimeConfigPath = configPath;
1442
+ setRuntimeLoader(loader, hash) {
1411
1443
  this.runtimeLoader = loader;
1412
- this.runtimeLoaderOptions = loaderOptions;
1444
+ this.runtimeHash = hash ?? null;
1445
+ this.updateAvailable.set(false);
1446
+ this.lastRefreshFailed.set(false);
1413
1447
  }
1414
- /**
1415
- * Internal method to configure runtime theme with config source information.
1416
- * @internal
1417
- */
1418
- configureRuntimeWithSource(config, source) {
1419
- this.isUsingFallbackConfig = source === 'fallback';
1420
- this.configureRuntime(config);
1448
+ async checkForThemeUpdates(loader, event) {
1449
+ this.runtimeLoader = loader;
1450
+ if (event?.resource && event.resource !== 'theme' && event.resource !== 'both') {
1451
+ return;
1452
+ }
1453
+ const eventHash = event?.hash;
1454
+ const eventUrl = event?.url?.toString?.() ?? event?.url;
1455
+ const eventTheme = event?.resource === 'theme' || event?.resource === 'both' ? event.theme : undefined;
1456
+ if (eventHash) {
1457
+ if (eventUrl) {
1458
+ const knownEventHash = this.runtimeEventHashes.get(eventUrl);
1459
+ if (knownEventHash && knownEventHash === eventHash) {
1460
+ return;
1461
+ }
1462
+ }
1463
+ if (eventHash === this.runtimeHash) {
1464
+ return;
1465
+ }
1466
+ if (!this.updateAvailable()) {
1467
+ this.updateAvailable.set(true);
1468
+ }
1469
+ if (eventUrl) {
1470
+ this.runtimeEventHashes.set(eventUrl, eventHash);
1471
+ }
1472
+ if (eventTheme) {
1473
+ this.pendingUpdatedThemes.add(eventTheme);
1474
+ }
1475
+ return;
1476
+ }
1477
+ const currentHash = this.runtimeHash;
1478
+ if (currentHash) {
1479
+ const check = await loader.checkForUpdates(currentHash);
1480
+ if (!check.updated || this.updateAvailable()) {
1481
+ return;
1482
+ }
1483
+ this.updateAvailable.set(true);
1484
+ return;
1485
+ }
1486
+ if (!this.updateAvailable()) {
1487
+ this.updateAvailable.set(true);
1488
+ }
1421
1489
  }
1422
- /**
1423
- * Manually reload the runtime theme configuration from the configured path.
1424
- * Useful for hot-reload scenarios or programmatic refresh.
1425
- */
1426
- async reloadRuntimeConfig() {
1427
- if (!this.runtimeConfigPath || !this.runtimeLoader || !this.runtimeLoaderOptions) {
1490
+ async refreshTheme(loader) {
1491
+ const runtimeLoader = loader ?? this.runtimeLoader;
1492
+ if (!runtimeLoader) {
1493
+ this.logger.warn('Theme refresh requested without runtime loader', {
1494
+ component: 'ThemeService',
1495
+ action: 'refreshTheme',
1496
+ });
1497
+ return;
1498
+ }
1499
+ if (!this.refreshHandler) {
1500
+ this.logger.warn('Theme refresh requested without handler', {
1501
+ component: 'ThemeService',
1502
+ action: 'refreshTheme',
1503
+ });
1428
1504
  return;
1429
1505
  }
1430
1506
  try {
1431
- const result = await this.runtimeLoader.load(this.runtimeConfigPath, this.runtimeLoaderOptions);
1432
- this.configureRuntime(result.data);
1507
+ const updatedThemes = Array.from(this.pendingUpdatedThemes);
1508
+ this.pendingUpdatedThemes.clear();
1509
+ await this.refreshHandler(updatedThemes);
1510
+ this.updateAvailable.set(false);
1511
+ this.lastRefreshFailed.set(false);
1433
1512
  }
1434
1513
  catch (error) {
1435
- if (this.runtimeLoaderOptions.logErrors !== false) {
1436
- this.logger.error(`Error reloading runtime config from ${this.runtimeConfigPath}`, error, {
1437
- component: 'ThemeService',
1438
- action: 'reloadRuntimeConfig',
1439
- configPath: this.runtimeConfigPath,
1440
- });
1441
- }
1442
- // Don't update config on reload error - keep existing config
1514
+ this.lastRefreshFailed.set(true);
1515
+ this.logger.error('Theme refresh failed', error, {
1516
+ component: 'ThemeService',
1517
+ action: 'refreshTheme',
1518
+ });
1443
1519
  }
1444
1520
  }
1445
1521
  init() {
1446
1522
  this.getAvailableThemes();
1447
1523
  }
1448
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: ThemeService, deps: [{ token: THEME_CONFIG_TOKEN, optional: true }, { token: RUNTIME_THEME_CONFIG_TOKEN, optional: true }], target: i0.ɵɵFactoryTarget.Injectable });
1524
+ setRefreshHandler(handler) {
1525
+ this.refreshHandler = handler;
1526
+ }
1527
+ async waitForFonts() {
1528
+ if (typeof document === 'undefined' || !document.fonts?.ready) {
1529
+ return;
1530
+ }
1531
+ try {
1532
+ await document.fonts.ready;
1533
+ }
1534
+ catch (error) {
1535
+ this.logger.warn('Font readiness check failed', {
1536
+ component: 'ThemeService',
1537
+ action: 'waitForFonts',
1538
+ error: error instanceof Error ? error.message : String(error),
1539
+ });
1540
+ }
1541
+ }
1542
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: ThemeService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
1449
1543
  static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: ThemeService, providedIn: 'root' });
1450
1544
  }
1451
1545
  i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: ThemeService, decorators: [{
1452
1546
  type: Injectable,
1453
1547
  args: [{ providedIn: 'root' }]
1454
- }], ctorParameters: () => [{ type: undefined, decorators: [{
1455
- type: Inject,
1456
- args: [THEME_CONFIG_TOKEN]
1457
- }, {
1458
- type: Optional
1459
- }] }, { type: undefined, decorators: [{
1460
- type: Inject,
1461
- args: [RUNTIME_THEME_CONFIG_TOKEN]
1462
- }, {
1463
- type: Optional
1464
- }] }] });
1465
-
1466
- /**
1467
- * Theme-specific IndexedDB database name for resource caching
1468
- */
1469
- const THEME_INDEXED_DB_NAME = 'sixbell-theme';
1470
- const RUNTIME_THEME_LOADER_DEFAULTS = {
1471
- cacheName: 'theme-runtime-config',
1472
- indexedDBName: THEME_INDEXED_DB_NAME,
1473
- storageOrder: ['indexedDB'],
1474
- cacheTTL: 1000 * 60 * 60 * 24,
1475
- freshOnNavigation: true, // Hot-reload on every navigation by default
1476
- staleWhileRevalidate: true,
1477
- useStaleOnError: true,
1478
- revalidateOnFresh: true,
1479
- retries: 3,
1480
- retryDelayMs: 500,
1481
- timeoutMs: 8000,
1482
- seedCacheWithFallback: true,
1483
- logErrors: true,
1484
- };
1548
+ }], ctorParameters: () => [] });
1485
1549
 
1486
- function buildRuntimeThemeLoaderOptions(configPath, overrides) {
1487
- const merged = { ...RUNTIME_THEME_LOADER_DEFAULTS, ...overrides };
1488
- return {
1489
- ...merged,
1490
- cacheKey: overrides?.cacheKey ?? configPath,
1491
- fallbackData: overrides?.fallbackData ?? FALLBACK_RUNTIME_THEME_CONFIG,
1492
- parser: overrides?.parser ?? (async (response) => (await response.json())),
1493
- };
1494
- }
1495
- /**
1496
- * @deprecated Use provideRuntimeTheme instead.
1497
- */
1498
- function provideTheme(config) {
1499
- return makeEnvironmentProviders([
1500
- {
1501
- provide: THEME_CONFIG_TOKEN,
1502
- useValue: (config || {}),
1503
- },
1504
- provideAppInitializer(() => inject(ThemeService).init()),
1505
- ]);
1506
- }
1507
1550
  function provideRuntimeTheme(configPath, options) {
1508
- const initialConfig = options?.loaderOptions?.fallbackData ?? FALLBACK_RUNTIME_THEME_CONFIG;
1509
1551
  return makeEnvironmentProviders([
1510
- {
1511
- provide: RUNTIME_THEME_CONFIG_TOKEN,
1512
- useValue: initialConfig,
1513
- },
1514
1552
  provideAppInitializer(() => {
1515
1553
  const themeService = inject(ThemeService);
1554
+ const storageService = inject(ThemeStorageService);
1516
1555
  const logger = inject(LoggerService);
1517
- // Create loader with global logger
1518
- const loader = options?.loader ?? new ResourceLoader(RUNTIME_THEME_LOADER_DEFAULTS, logger);
1556
+ const configStore = new RuntimeConfigStore('theme-runtime-config', options?.appId);
1557
+ const themeStore = new RuntimeConfigStore('theme-runtime-config', options?.appId);
1558
+ const configLoader = new RuntimeConfigLoader(configPath, {
1559
+ fallbackData: {
1560
+ meta: {
1561
+ name: DEFAULT_BASE_THEME,
1562
+ updatedAt: new Date().toISOString(),
1563
+ hash: 'fallback-hash',
1564
+ schemaVersion: THEME_SCHEMA_VERSION,
1565
+ },
1566
+ themes: [configPath],
1567
+ defaultTheme: DEFAULT_BASE_THEME,
1568
+ defaultScheme: DEFAULT_SCHEME,
1569
+ },
1570
+ schemaVersion: THEME_SCHEMA_VERSION,
1571
+ resource: 'theme',
1572
+ store: configStore,
1573
+ logger,
1574
+ parser: async (response) => (await response.json()),
1575
+ appId: options?.appId,
1576
+ });
1577
+ const updateAdapter = new RuntimeUpdateAdapter(async (event) => {
1578
+ if (event.resource && event.resource !== 'theme' && event.resource !== 'both') {
1579
+ return;
1580
+ }
1581
+ await themeService.checkForThemeUpdates(configLoader, event);
1582
+ });
1583
+ if (options?.sse) {
1584
+ updateAdapter.connectSse(options.sse.url, {
1585
+ resource: 'theme',
1586
+ withCredentials: options.sse.withCredentials,
1587
+ eventType: options.sse.eventType,
1588
+ transform: options.sse.transform,
1589
+ logger,
1590
+ });
1591
+ }
1592
+ if (options?.updateStream) {
1593
+ updateAdapter.connectStream(options.updateStream);
1594
+ }
1595
+ const loadThemeConfig = async (themePath, loadOptions) => {
1596
+ const themeLoader = new RuntimeConfigLoader(themePath, {
1597
+ fallbackData: FALLBACK_RUNTIME_THEME_CONFIG,
1598
+ schemaVersion: THEME_SCHEMA_VERSION,
1599
+ resource: 'theme',
1600
+ store: themeStore,
1601
+ logger,
1602
+ parser: async (response) => (await response.json()),
1603
+ appId: options?.appId,
1604
+ });
1605
+ let result = loadOptions?.forceRefresh ? await themeLoader.refresh() : await themeLoader.loadLatest();
1606
+ if (!loadOptions?.forceRefresh && result.source === 'cache') {
1607
+ try {
1608
+ const check = await themeLoader.checkForUpdates(result.hash);
1609
+ if (check.updated) {
1610
+ result = await themeLoader.refresh();
1611
+ }
1612
+ }
1613
+ catch (error) {
1614
+ logger.warn('Theme entry bootstrap validation failed', {
1615
+ component: 'ThemeProvider',
1616
+ action: 'validateEntry',
1617
+ theme: themePath,
1618
+ error: error instanceof Error ? error.message : String(error),
1619
+ });
1620
+ }
1621
+ }
1622
+ if (!result.meta.schemaVersion) {
1623
+ throw new Error(`Theme schemaVersion missing for ${themePath}`);
1624
+ }
1625
+ if (result.meta.schemaVersion !== THEME_SCHEMA_VERSION) {
1626
+ throw new Error(`Theme schemaVersion mismatch for ${themePath}`);
1627
+ }
1628
+ if (!result.data.meta?.name) {
1629
+ throw new Error(`Theme meta.name missing for ${themePath}`);
1630
+ }
1631
+ if (!result.data.meta?.hash) {
1632
+ throw new Error(`Theme meta.hash missing for ${themePath}`);
1633
+ }
1634
+ if (!result.data.meta?.updatedAt) {
1635
+ throw new Error(`Theme meta.updatedAt missing for ${themePath}`);
1636
+ }
1637
+ return result.data;
1638
+ };
1639
+ const applyThemeConfig = async (config, blocking) => {
1640
+ const themeName = config.meta?.name;
1641
+ if (!themeName) {
1642
+ throw new Error('Theme meta.name missing for config apply');
1643
+ }
1644
+ const normalizedConfig = {
1645
+ ...config,
1646
+ themes: {
1647
+ light: {
1648
+ ...config.themes.light,
1649
+ prefersDark: false,
1650
+ },
1651
+ dark: {
1652
+ ...config.themes.dark,
1653
+ prefersDark: true,
1654
+ },
1655
+ },
1656
+ };
1657
+ await themeService.configureRuntime(normalizedConfig, themeName, { blocking });
1658
+ };
1519
1659
  return (async () => {
1520
- const loaderOptions = buildRuntimeThemeLoaderOptions(configPath, options?.loaderOptions);
1521
- // Set up runtime loader and navigation listener
1522
- themeService.setRuntimeLoader(configPath, loader, loaderOptions);
1660
+ themeService.init();
1661
+ let configResult;
1523
1662
  try {
1524
- const result = await loader.load(configPath, loaderOptions);
1525
- // Pass the source so service knows if using cache, network, or fallback
1526
- themeService.configureRuntimeWithSource(result.data, result.source);
1663
+ configResult = await configLoader.loadLatest();
1527
1664
  }
1528
1665
  catch (error) {
1529
- if (loaderOptions.logErrors !== false) {
1530
- logger.error(`Error loading runtime config from ${configPath}`, error, {
1666
+ logger.error('Theme config load failed', error, {
1667
+ component: 'ThemeProvider',
1668
+ action: 'loadLatest',
1669
+ });
1670
+ return;
1671
+ }
1672
+ if (configResult.source === 'cache') {
1673
+ try {
1674
+ const check = await configLoader.checkForUpdates(configResult.hash);
1675
+ if (check.updated) {
1676
+ configResult = await configLoader.refresh();
1677
+ }
1678
+ }
1679
+ catch (error) {
1680
+ logger.warn('Theme config bootstrap validation failed', {
1681
+ component: 'ThemeProvider',
1682
+ action: 'bootstrapValidation',
1683
+ error: error instanceof Error ? error.message : String(error),
1684
+ });
1685
+ }
1686
+ }
1687
+ const themeConfig = configResult.data;
1688
+ if (!themeConfig.meta.schemaVersion) {
1689
+ logger.error('Theme config schemaVersion missing', undefined, {
1690
+ component: 'ThemeProvider',
1691
+ action: 'validateSchema',
1692
+ });
1693
+ return;
1694
+ }
1695
+ if (themeConfig.meta.schemaVersion !== THEME_SCHEMA_VERSION) {
1696
+ logger.error('Theme config schemaVersion mismatch', undefined, {
1697
+ component: 'ThemeProvider',
1698
+ action: 'validateSchema',
1699
+ expected: THEME_SCHEMA_VERSION,
1700
+ actual: themeConfig.meta.schemaVersion,
1701
+ });
1702
+ return;
1703
+ }
1704
+ if (!themeConfig.meta.hash) {
1705
+ logger.error('Theme config hash missing', undefined, {
1706
+ component: 'ThemeProvider',
1707
+ action: 'validateSchema',
1708
+ });
1709
+ return;
1710
+ }
1711
+ if (!themeConfig.meta.updatedAt) {
1712
+ logger.error('Theme config updatedAt missing', undefined, {
1713
+ component: 'ThemeProvider',
1714
+ action: 'validateSchema',
1715
+ });
1716
+ return;
1717
+ }
1718
+ const themePaths = themeConfig.themes ?? [];
1719
+ const themeEntries = new Map();
1720
+ const availableThemes = [];
1721
+ for (const themePath of themePaths) {
1722
+ try {
1723
+ const loadedConfig = await loadThemeConfig(themePath);
1724
+ const themeName = loadedConfig.meta?.name;
1725
+ if (!themeName) {
1726
+ logger.warn('Theme meta.name missing', {
1727
+ component: 'ThemeProvider',
1728
+ action: 'resolveThemeName',
1729
+ path: themePath,
1730
+ });
1731
+ continue;
1732
+ }
1733
+ if (themeConfig.excludeThemes?.includes(themeName)) {
1734
+ continue;
1735
+ }
1736
+ themeEntries.set(themeName, themePath);
1737
+ availableThemes.push(themeName);
1738
+ }
1739
+ catch (error) {
1740
+ logger.warn('Failed to load theme entry', {
1741
+ component: 'ThemeProvider',
1742
+ action: 'loadThemeEntry',
1743
+ path: themePath,
1744
+ error: error instanceof Error ? error.message : String(error),
1745
+ });
1746
+ }
1747
+ }
1748
+ const defaultTheme = resolveDefaultTheme(themeConfig.defaultTheme, availableThemes);
1749
+ const config = {
1750
+ availableThemes,
1751
+ defaultTheme,
1752
+ defaultScheme: themeConfig.defaultScheme ?? DEFAULT_SCHEME,
1753
+ };
1754
+ themeService.applyRuntimeConfig(config, configResult.source);
1755
+ themeService.setRuntimeLoader(configLoader, configResult.hash);
1756
+ themeService.setRefreshHandler(async (updatedThemes) => {
1757
+ let refreshedConfig;
1758
+ try {
1759
+ refreshedConfig = await configLoader.refresh();
1760
+ }
1761
+ catch (error) {
1762
+ logger.error('Theme config refresh failed', error, {
1763
+ component: 'ThemeProvider',
1764
+ action: 'refresh',
1765
+ });
1766
+ return;
1767
+ }
1768
+ if (!refreshedConfig.data.meta.schemaVersion) {
1769
+ logger.error('Theme config schemaVersion missing', undefined, {
1531
1770
  component: 'ThemeProvider',
1532
- action: 'provideRuntimeTheme',
1533
- configPath,
1771
+ action: 'validateSchema',
1534
1772
  });
1773
+ return;
1535
1774
  }
1536
- // When catching error, we're using fallback
1537
- themeService.configureRuntimeWithSource(loaderOptions.fallbackData ?? FALLBACK_RUNTIME_THEME_CONFIG, 'fallback');
1775
+ if (refreshedConfig.data.meta.schemaVersion !== THEME_SCHEMA_VERSION) {
1776
+ logger.error('Theme config schemaVersion mismatch', undefined, {
1777
+ component: 'ThemeProvider',
1778
+ action: 'validateSchema',
1779
+ expected: THEME_SCHEMA_VERSION,
1780
+ actual: refreshedConfig.data.meta.schemaVersion,
1781
+ });
1782
+ return;
1783
+ }
1784
+ if (!refreshedConfig.data.meta.hash) {
1785
+ logger.error('Theme config hash missing', undefined, {
1786
+ component: 'ThemeProvider',
1787
+ action: 'validateSchema',
1788
+ });
1789
+ return;
1790
+ }
1791
+ if (!refreshedConfig.data.meta.updatedAt) {
1792
+ logger.error('Theme config updatedAt missing', undefined, {
1793
+ component: 'ThemeProvider',
1794
+ action: 'validateSchema',
1795
+ });
1796
+ return;
1797
+ }
1798
+ const refreshedPaths = refreshedConfig.data.themes ?? [];
1799
+ const refreshedEntries = new Map();
1800
+ const refreshedAvailableThemes = [];
1801
+ for (const themePath of refreshedPaths) {
1802
+ try {
1803
+ const loadedConfig = await loadThemeConfig(themePath);
1804
+ const themeName = loadedConfig.meta?.name;
1805
+ if (!themeName) {
1806
+ logger.warn('Theme meta.name missing', {
1807
+ component: 'ThemeProvider',
1808
+ action: 'resolveThemeName',
1809
+ path: themePath,
1810
+ });
1811
+ continue;
1812
+ }
1813
+ if (refreshedConfig.data.excludeThemes?.includes(themeName)) {
1814
+ continue;
1815
+ }
1816
+ refreshedEntries.set(themeName, themePath);
1817
+ refreshedAvailableThemes.push(themeName);
1818
+ }
1819
+ catch (error) {
1820
+ logger.warn('Failed to load theme entry', {
1821
+ component: 'ThemeProvider',
1822
+ action: 'loadThemeEntry',
1823
+ path: themePath,
1824
+ error: error instanceof Error ? error.message : String(error),
1825
+ });
1826
+ }
1827
+ }
1828
+ const refreshedDefaultTheme = resolveDefaultTheme(refreshedConfig.data.defaultTheme, refreshedAvailableThemes);
1829
+ const refreshedSelected = themeService.selectedTheme();
1830
+ const configHashChanged = refreshedConfig.hash !== configResult.hash;
1831
+ const changedEntries = configHashChanged
1832
+ ? refreshedEntries
1833
+ : new Map([...refreshedEntries].filter(([name]) => updatedThemes.includes(name)));
1834
+ if (configHashChanged) {
1835
+ themeService.applyRuntimeConfig({
1836
+ availableThemes: refreshedAvailableThemes,
1837
+ defaultTheme: refreshedDefaultTheme,
1838
+ defaultScheme: refreshedConfig.data.defaultScheme ?? DEFAULT_SCHEME,
1839
+ }, refreshedConfig.source);
1840
+ themeService.setRuntimeLoader(configLoader, refreshedConfig.hash);
1841
+ configResult = refreshedConfig;
1842
+ const refreshedPath = refreshedEntries.get(refreshedSelected) ?? [...refreshedEntries.values()][0];
1843
+ if (refreshedPath) {
1844
+ const refreshedThemeConfig = await loadThemeConfig(refreshedPath, { forceRefresh: true });
1845
+ await applyThemeConfig(refreshedThemeConfig, true);
1846
+ }
1847
+ return;
1848
+ }
1849
+ if (!changedEntries.size) {
1850
+ return;
1851
+ }
1852
+ for (const [name, path] of changedEntries) {
1853
+ const refreshedThemeConfig = await loadThemeConfig(path, { forceRefresh: true });
1854
+ const isSelected = name === refreshedSelected;
1855
+ await applyThemeConfig(refreshedThemeConfig, isSelected);
1856
+ }
1857
+ });
1858
+ const savedTheme = storageService.getSavedTheme();
1859
+ const selectedTheme = savedTheme && availableThemes.includes(savedTheme) ? savedTheme : config.defaultTheme;
1860
+ const selectedPath = themeEntries.get(selectedTheme) ?? [...themeEntries.values()][0];
1861
+ if (!selectedPath) {
1862
+ logger.warn('No theme entries available in config', {
1863
+ component: 'ThemeProvider',
1864
+ action: 'provideRuntimeTheme',
1865
+ });
1866
+ return;
1867
+ }
1868
+ const selectedConfig = await loadThemeConfig(selectedPath);
1869
+ await applyThemeConfig(selectedConfig, true);
1870
+ const remainingEntries = [...themeEntries.entries()].filter(([name]) => name !== selectedTheme);
1871
+ for (const [, path] of remainingEntries) {
1872
+ loadThemeConfig(path)
1873
+ .then((configToApply) => applyThemeConfig(configToApply, false))
1874
+ .catch(() => undefined);
1538
1875
  }
1539
1876
  })();
1540
1877
  }),
@@ -1545,5 +1882,5 @@ function provideRuntimeTheme(configPath, options) {
1545
1882
  * Generated bundle index. Do not edit.
1546
1883
  */
1547
1884
 
1548
- export { DARK_MODE_MEDIA_QUERY, DARK_THEME_CLASS, DEFAULT_BASE_THEME, DEFAULT_SCHEME, DEFAULT_THEMES, DEFAULT_THEME_CODES, FALLBACK_RUNTIME_THEME_CONFIG, RUNTIME_THEME_CONFIG_TOKEN, THEME_ATTRIBUTE_NAME, THEME_CONFIG_TOKEN, THEME_SCHEME_SEPARATOR, THEME_STORAGE_NAMESPACE, THEME_STORAGE_SCHEME_KEY, THEME_STORAGE_THEME_KEY, ThemeAssetsService, ThemeDomService, ThemeSchemeService, ThemeService, ThemeStorageService, VALID_SCHEMES, buildAvailableThemes, buildThemeIdentifier, formatSchemeName, formatThemeName, hasLocalStorage, isThemeAvailable, isValidScheme, parseThemeIdentifier, provideRuntimeTheme, provideTheme, resolveDefaultTheme, supportsMediaQuery, validateThemeConfig };
1885
+ export { DEFAULT_BASE_THEME, DEFAULT_SCHEME, FALLBACK_RUNTIME_THEME_CONFIG, THEME_SCHEMA_VERSION, ThemeAssetsService, ThemeDomService, ThemeSchemeService, ThemeService, ThemeStorageService, VALID_SCHEMES, buildThemeIdentifier, formatSchemeName, formatThemeName, hasLocalStorage, isThemeAvailable, isValidScheme, parseThemeIdentifier, provideRuntimeTheme, resolveDefaultTheme, supportsMediaQuery, validateThemeConfig };
1549
1886
  //# sourceMappingURL=sixbell-telco-sdk-utils-theme.mjs.map