@sixbell-telco/sdk 1.6.0 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (209) hide show
  1. package/CHANGELOG.md +260 -711
  2. package/README.md +337 -278
  3. package/_index.css +3 -3
  4. package/components/accordion/accordion-item/accordion-item.component.d.ts +3 -4
  5. package/components/audio-player/audio-timeline/audio-timeline.component.d.ts +29 -2
  6. package/components/audio-player/services/audio.service.d.ts +14 -14
  7. package/components/audio-player/src/audio-player.component.d.ts +7 -3
  8. package/components/audio-player/volume-control/volume-control.component.d.ts +28 -1
  9. package/components/button/src/button.component.d.ts +46 -1
  10. package/components/countdown/src/countdown.component.d.ts +1 -1
  11. package/components/data-table/data-table-empty-actions/data-table-empty-actions.component.d.ts +5 -0
  12. package/components/data-table/public-api.d.ts +1 -0
  13. package/components/data-table/src/data-table.component.d.ts +11 -3
  14. package/components/dialog/src/dialog.component.d.ts +51 -5
  15. package/components/dropdown/dropdown-content/dropdown-content.component.d.ts +2 -1
  16. package/components/dropdown/dropdown-item/dropdown-item.component.d.ts +37 -1
  17. package/components/dropdown/dropdown-item-checkbox/dropdown-item-checkbox.component.d.ts +33 -1
  18. package/components/dropdown/dropdown-item-radio/dropdown-item-radio.component.d.ts +33 -1
  19. package/components/dropdown/dropdown-trigger/dropdown-trigger.component.d.ts +53 -2
  20. package/components/dropdown/src/dropdown.component.d.ts +2 -2
  21. package/components/dropdown-menu/bar/dropdown-menu-bar-content/dropdown-menu-bar-content.component.d.ts +2 -1
  22. package/components/dropdown-menu/bar/dropdown-menu-bar-item/dropdown-menu-bar-item.component.d.ts +33 -1
  23. package/components/dropdown-menu/bar/dropdown-menu-bar-item-checkbox/dropdown-menu-bar-item-checkbox.component.d.ts +33 -1
  24. package/components/dropdown-menu/bar/dropdown-menu-bar-item-radio/dropdown-menu-bar-item-radio.component.d.ts +33 -1
  25. package/components/dropdown-menu/src/directives/dropdown-menu.directive.d.ts +1 -3
  26. package/components/dropdown-menu/src/dropdown-menu-content/dropdown-menu-content.component.d.ts +4 -4
  27. package/components/dropdown-menu/src/dropdown-menu-item/dropdown-menu-item.component.d.ts +33 -1
  28. package/components/dropdown-menu/src/dropdown-menu-sub-content/dropdown-menu-sub-content.component.d.ts +2 -1
  29. package/components/dual-list/src/dual-list.component.d.ts +4 -2
  30. package/components/file-upload/file-dropzone/file-dropzone.component.d.ts +53 -8
  31. package/components/file-upload/file-uploader/file-uploader.component.d.ts +40 -9
  32. package/components/forms/checkbox/src/checkbox.component.d.ts +46 -2
  33. package/components/forms/combobox/src/combobox.component.d.ts +40 -5
  34. package/components/forms/date-picker/src/date-picker.component.d.ts +11 -1
  35. package/components/forms/form-group/README.md +114 -0
  36. package/components/forms/form-group/index.d.ts +5 -0
  37. package/components/forms/form-group/public-api.d.ts +1 -0
  38. package/components/forms/form-group/src/form-group.component.d.ts +150 -0
  39. package/components/forms/form-item/README.md +17 -0
  40. package/components/forms/form-item/index.d.ts +5 -0
  41. package/components/forms/form-item/public-api.d.ts +1 -0
  42. package/components/forms/form-item/src/form-item.component.d.ts +5 -0
  43. package/components/forms/input/src/input.component.d.ts +45 -2
  44. package/components/forms/radio/src/radio.component.d.ts +46 -2
  45. package/components/forms/range/src/range.component.d.ts +38 -1
  46. package/components/forms/select/src/select.component.d.ts +40 -5
  47. package/components/forms/switch/src/switch.component.d.ts +46 -2
  48. package/components/forms/textarea/src/textarea.component.d.ts +62 -12
  49. package/components/forms/toggle/src/toggle.component.d.ts +46 -1
  50. package/components/link/src/link.component.d.ts +0 -3
  51. package/components/overlay/overlay-content/overlay-content.component.d.ts +2 -1
  52. package/components/overlay/overlay-trigger/overlay-trigger.component.d.ts +37 -5
  53. package/components/overlay/src/overlay.component.d.ts +4 -5
  54. package/components/paginator/components/pagination-item/pagination-item.component.d.ts +37 -1
  55. package/components/tab/directives/tab-content/tab-content.directive.d.ts +5 -6
  56. package/components/tab/directives/tab-header/tab-header.directive.d.ts +2 -2
  57. package/components/table/public-api.d.ts +1 -0
  58. package/components/table/src/table.component.d.ts +36 -4
  59. package/components/table/table-empty-actions/table-empty-actions.component.d.ts +5 -0
  60. package/components/table/table-header-checkbox/table-header-checkbox.component.d.ts +5 -11
  61. package/components/table/table-row-checkbox/table-row-checkbox.component.d.ts +5 -11
  62. package/components/toast/toast-message/toast-message.component.d.ts +42 -1
  63. package/components/tooltip/src/tooltip.component.d.ts +10 -1
  64. package/components/wizard/services/wizard.service.d.ts +5 -5
  65. package/components/wizard/wizard-marker/wizard-marker.component.d.ts +2 -3
  66. package/directives/auto-focus/public-api.d.ts +1 -1
  67. package/directives/auto-focus/src/{autofocus.directive.d.ts → auto-focus.directive.d.ts} +9 -15
  68. package/directives/click-outside/src/click-outside.directive.d.ts +1 -3
  69. package/directives/only-numbers/public-api.d.ts +6 -1
  70. package/directives/only-numbers/src/only-numbers.directive.d.ts +36 -0
  71. package/fesm2022/sixbell-telco-sdk-components-accordion.mjs +6 -9
  72. package/fesm2022/sixbell-telco-sdk-components-accordion.mjs.map +1 -1
  73. package/fesm2022/sixbell-telco-sdk-components-audio-player.mjs +133 -51
  74. package/fesm2022/sixbell-telco-sdk-components-audio-player.mjs.map +1 -1
  75. package/fesm2022/sixbell-telco-sdk-components-avatar.mjs +1 -1
  76. package/fesm2022/sixbell-telco-sdk-components-avatar.mjs.map +1 -1
  77. package/fesm2022/sixbell-telco-sdk-components-badge.mjs +2 -2
  78. package/fesm2022/sixbell-telco-sdk-components-badge.mjs.map +1 -1
  79. package/fesm2022/sixbell-telco-sdk-components-button.mjs +78 -4
  80. package/fesm2022/sixbell-telco-sdk-components-button.mjs.map +1 -1
  81. package/fesm2022/sixbell-telco-sdk-components-countdown.mjs.map +1 -1
  82. package/fesm2022/sixbell-telco-sdk-components-data-table-sub-component-toggle.mjs +1 -1
  83. package/fesm2022/sixbell-telco-sdk-components-data-table-sub-component-toggle.mjs.map +1 -1
  84. package/fesm2022/sixbell-telco-sdk-components-data-table.mjs +53 -27
  85. package/fesm2022/sixbell-telco-sdk-components-data-table.mjs.map +1 -1
  86. package/fesm2022/sixbell-telco-sdk-components-dialog.mjs +82 -12
  87. package/fesm2022/sixbell-telco-sdk-components-dialog.mjs.map +1 -1
  88. package/fesm2022/sixbell-telco-sdk-components-dropdown-menu-bar.mjs +166 -13
  89. package/fesm2022/sixbell-telco-sdk-components-dropdown-menu-bar.mjs.map +1 -1
  90. package/fesm2022/sixbell-telco-sdk-components-dropdown-menu.mjs +68 -24
  91. package/fesm2022/sixbell-telco-sdk-components-dropdown-menu.mjs.map +1 -1
  92. package/fesm2022/sixbell-telco-sdk-components-dropdown.mjs +283 -16
  93. package/fesm2022/sixbell-telco-sdk-components-dropdown.mjs.map +1 -1
  94. package/fesm2022/sixbell-telco-sdk-components-dual-list.mjs +12 -9
  95. package/fesm2022/sixbell-telco-sdk-components-dual-list.mjs.map +1 -1
  96. package/fesm2022/sixbell-telco-sdk-components-file-upload.mjs +151 -10
  97. package/fesm2022/sixbell-telco-sdk-components-file-upload.mjs.map +1 -1
  98. package/fesm2022/sixbell-telco-sdk-components-forms-checkbox.mjs +69 -3
  99. package/fesm2022/sixbell-telco-sdk-components-forms-checkbox.mjs.map +1 -1
  100. package/fesm2022/sixbell-telco-sdk-components-forms-combobox.mjs +96 -19
  101. package/fesm2022/sixbell-telco-sdk-components-forms-combobox.mjs.map +1 -1
  102. package/fesm2022/sixbell-telco-sdk-components-forms-date-picker.mjs +15 -3
  103. package/fesm2022/sixbell-telco-sdk-components-forms-date-picker.mjs.map +1 -1
  104. package/fesm2022/sixbell-telco-sdk-components-forms-form-error.mjs +2 -2
  105. package/fesm2022/sixbell-telco-sdk-components-forms-form-error.mjs.map +1 -1
  106. package/fesm2022/sixbell-telco-sdk-components-forms-form-group.mjs +159 -0
  107. package/fesm2022/sixbell-telco-sdk-components-forms-form-group.mjs.map +1 -0
  108. package/fesm2022/sixbell-telco-sdk-components-forms-form-item.mjs +20 -0
  109. package/fesm2022/sixbell-telco-sdk-components-forms-form-item.mjs.map +1 -0
  110. package/fesm2022/sixbell-telco-sdk-components-forms-input.mjs +62 -6
  111. package/fesm2022/sixbell-telco-sdk-components-forms-input.mjs.map +1 -1
  112. package/fesm2022/sixbell-telco-sdk-components-forms-radio.mjs +69 -3
  113. package/fesm2022/sixbell-telco-sdk-components-forms-radio.mjs.map +1 -1
  114. package/fesm2022/sixbell-telco-sdk-components-forms-range.mjs +57 -4
  115. package/fesm2022/sixbell-telco-sdk-components-forms-range.mjs.map +1 -1
  116. package/fesm2022/sixbell-telco-sdk-components-forms-select.mjs +91 -20
  117. package/fesm2022/sixbell-telco-sdk-components-forms-select.mjs.map +1 -1
  118. package/fesm2022/sixbell-telco-sdk-components-forms-switch.mjs +80 -6
  119. package/fesm2022/sixbell-telco-sdk-components-forms-switch.mjs.map +1 -1
  120. package/fesm2022/sixbell-telco-sdk-components-forms-textarea.mjs +131 -13
  121. package/fesm2022/sixbell-telco-sdk-components-forms-textarea.mjs.map +1 -1
  122. package/fesm2022/sixbell-telco-sdk-components-forms-toggle.mjs +69 -3
  123. package/fesm2022/sixbell-telco-sdk-components-forms-toggle.mjs.map +1 -1
  124. package/fesm2022/sixbell-telco-sdk-components-link.mjs +2 -7
  125. package/fesm2022/sixbell-telco-sdk-components-link.mjs.map +1 -1
  126. package/fesm2022/sixbell-telco-sdk-components-overlay.mjs +94 -42
  127. package/fesm2022/sixbell-telco-sdk-components-overlay.mjs.map +1 -1
  128. package/fesm2022/sixbell-telco-sdk-components-paginator.mjs +71 -10
  129. package/fesm2022/sixbell-telco-sdk-components-paginator.mjs.map +1 -1
  130. package/fesm2022/sixbell-telco-sdk-components-tab.mjs +5 -9
  131. package/fesm2022/sixbell-telco-sdk-components-tab.mjs.map +1 -1
  132. package/fesm2022/sixbell-telco-sdk-components-table.mjs +131 -47
  133. package/fesm2022/sixbell-telco-sdk-components-table.mjs.map +1 -1
  134. package/fesm2022/sixbell-telco-sdk-components-toast.mjs +69 -4
  135. package/fesm2022/sixbell-telco-sdk-components-toast.mjs.map +1 -1
  136. package/fesm2022/sixbell-telco-sdk-components-tooltip.mjs +15 -3
  137. package/fesm2022/sixbell-telco-sdk-components-tooltip.mjs.map +1 -1
  138. package/fesm2022/sixbell-telco-sdk-components-wizard.mjs +4 -4
  139. package/fesm2022/sixbell-telco-sdk-components-wizard.mjs.map +1 -1
  140. package/fesm2022/sixbell-telco-sdk-directives-auto-focus.mjs +29 -49
  141. package/fesm2022/sixbell-telco-sdk-directives-auto-focus.mjs.map +1 -1
  142. package/fesm2022/sixbell-telco-sdk-directives-click-outside.mjs +7 -10
  143. package/fesm2022/sixbell-telco-sdk-directives-click-outside.mjs.map +1 -1
  144. package/fesm2022/sixbell-telco-sdk-directives-only-numbers.mjs +48 -17
  145. package/fesm2022/sixbell-telco-sdk-directives-only-numbers.mjs.map +1 -1
  146. package/fesm2022/sixbell-telco-sdk-utils-date.mjs +1 -1
  147. package/fesm2022/sixbell-telco-sdk-utils-date.mjs.map +1 -1
  148. package/fesm2022/sixbell-telco-sdk-utils-pipes-to-bytes-extesion.mjs +1 -1
  149. package/fesm2022/sixbell-telco-sdk-utils-pipes-to-bytes-extesion.mjs.map +1 -1
  150. package/fesm2022/sixbell-telco-sdk-utils-runtime-config.mjs +339 -0
  151. package/fesm2022/sixbell-telco-sdk-utils-runtime-config.mjs.map +1 -0
  152. package/fesm2022/sixbell-telco-sdk-utils-sync.mjs +1 -1
  153. package/fesm2022/sixbell-telco-sdk-utils-sync.mjs.map +1 -1
  154. package/fesm2022/sixbell-telco-sdk-utils-theme.mjs +1062 -730
  155. package/fesm2022/sixbell-telco-sdk-utils-theme.mjs.map +1 -1
  156. package/fesm2022/sixbell-telco-sdk-utils-translation.mjs +350 -267
  157. package/fesm2022/sixbell-telco-sdk-utils-translation.mjs.map +1 -1
  158. package/package.json +55 -46
  159. package/utils/runtime-config/README.md +235 -0
  160. package/utils/{resource-loader → runtime-config}/index.d.ts +1 -1
  161. package/utils/runtime-config/public-api.d.ts +5 -0
  162. package/utils/runtime-config/src/http-client.d.ts +11 -0
  163. package/utils/runtime-config/src/runtime-config-loader.d.ts +23 -0
  164. package/utils/runtime-config/src/runtime-config-store.d.ts +11 -0
  165. package/utils/runtime-config/src/runtime-update-adapter.d.ts +15 -0
  166. package/utils/runtime-config/src/types.d.ts +66 -0
  167. package/utils/theme/README.md +324 -986
  168. package/utils/theme/public-api.d.ts +4 -4
  169. package/utils/theme/src/constants.d.ts +6 -12
  170. package/utils/theme/src/models/theme.d.ts +46 -173
  171. package/utils/theme/src/providers/theme.provider.d.ts +0 -10
  172. package/utils/theme/src/providers/theme.provider.types.d.ts +16 -15
  173. package/utils/theme/src/theme-assets/theme-assets.service.d.ts +16 -12
  174. package/utils/theme/src/theme-dom/theme-dom.service.d.ts +10 -3
  175. package/utils/theme/src/theme.service.d.ts +24 -27
  176. package/utils/theme/src/utils/utils.d.ts +2 -10
  177. package/utils/translation/README.md +170 -1390
  178. package/utils/translation/public-api.d.ts +3 -3
  179. package/utils/translation/src/constants.d.ts +7 -9
  180. package/utils/translation/src/models/translation.d.ts +9 -10
  181. package/utils/translation/src/providers/translation.provider.d.ts +17 -28
  182. package/utils/translation/src/providers/translation.provider.types.d.ts +13 -6
  183. package/utils/translation/src/translation-dom/translation-dom.service.d.ts +2 -3
  184. package/utils/translation/src/translation.service.d.ts +37 -9
  185. package/directives/only-numbers/src/just-numbers.directive.d.ts +0 -9
  186. package/fesm2022/sixbell-telco-sdk-utils-resource-loader.mjs +0 -1222
  187. package/fesm2022/sixbell-telco-sdk-utils-resource-loader.mjs.map +0 -1
  188. package/utils/resource-loader/README.md +0 -460
  189. package/utils/resource-loader/public-api.d.ts +0 -1
  190. package/utils/resource-loader/src/cache/index.d.ts +0 -2
  191. package/utils/resource-loader/src/cache/layers/factory.d.ts +0 -38
  192. package/utils/resource-loader/src/cache/layers/index.d.ts +0 -3
  193. package/utils/resource-loader/src/cache/layers/indexed-db-cache.d.ts +0 -118
  194. package/utils/resource-loader/src/cache/layers/local-storage-cache.d.ts +0 -86
  195. package/utils/resource-loader/src/cache/layers/memory-cache.d.ts +0 -76
  196. package/utils/resource-loader/src/cache/types.d.ts +0 -107
  197. package/utils/resource-loader/src/config/index.d.ts +0 -1
  198. package/utils/resource-loader/src/config/load-config.d.ts +0 -32
  199. package/utils/resource-loader/src/constants.d.ts +0 -38
  200. package/utils/resource-loader/src/http/index.d.ts +0 -1
  201. package/utils/resource-loader/src/http/retryable-client.d.ts +0 -43
  202. package/utils/resource-loader/src/index.d.ts +0 -1
  203. package/utils/resource-loader/src/resource-loader.d.ts +0 -67
  204. package/utils/resource-loader/src/types.d.ts +0 -152
  205. package/utils/resource-loader/src/utils/cache-validator.d.ts +0 -72
  206. package/utils/resource-loader/src/utils/helpers.d.ts +0 -15
  207. package/utils/resource-loader/src/utils/index.d.ts +0 -2
  208. package/utils/theme/src/providers/constants.d.ts +0 -7
  209. package/utils/translation/src/providers/constants.d.ts +0 -11
@@ -1,1222 +0,0 @@
1
- import { LoggerService } from '@sixbell-telco/sdk/utils/logger';
2
-
3
- /**
4
- * Default storage layer order for cache lookups.
5
- * IndexedDB is tried first (largest capacity), then localStorage, then memory (fastest but volatile).
6
- */
7
- const DEFAULT_STORAGE_ORDER = ['indexedDB', 'localStorage', 'memory'];
8
- /**
9
- * Default cache TTL: 24 hours (in milliseconds)
10
- */
11
- const DEFAULT_CACHE_TTL = 24 * 60 * 60 * 1000;
12
- /**
13
- * IndexedDB database and store names
14
- */
15
- const INDEXED_DB_NAME = 'resilient-resources';
16
- const INDEXED_DB_STORE_NAME = 'resources';
17
- /**
18
- * Default configuration for ResourceLoader instances.
19
- * These values are applied to all load operations unless explicitly overridden.
20
- *
21
- * Note: freshOnNavigation defaults to true, which is the recommended pattern:
22
- * - Skip cache on every load, always fetch fresh with network retry fallback to cache
23
- * - Prevents stale data problems and layout shifts
24
- * - Use fallbackData for offline scenarios
25
- * - Disable it (set to false) only if you need aggressive caching (rare cases)
26
- */
27
- const RESOURCE_LOADER_DEFAULTS = {
28
- cacheName: 'resilient-resource',
29
- storageOrder: DEFAULT_STORAGE_ORDER,
30
- cacheTTL: DEFAULT_CACHE_TTL,
31
- staleWhileRevalidate: true,
32
- useStaleOnError: true,
33
- revalidateOnFresh: false,
34
- retries: 3,
35
- retryDelayMs: 250,
36
- timeoutMs: 8000,
37
- seedCacheWithFallback: true,
38
- logErrors: true,
39
- freshOnNavigation: true,
40
- };
41
- /**
42
- * Maximum number of retry attempts for failed requests
43
- */
44
- const MAX_RETRIES = 5;
45
- /**
46
- * Cleanup interval for cache maintenance (24 hours)
47
- */
48
- const CACHE_CLEANUP_INTERVAL = 24 * 60 * 60 * 1000;
49
- /**
50
- * Maximum cleanup task duration (5 minutes)
51
- */
52
- const MAX_CLEANUP_TASK_DURATION = 5 * 60 * 1000;
53
-
54
- /**
55
- * Pure utility class for cache validation logic.
56
- * Determines whether a cache entry is fresh, stale, or expired.
57
- *
58
- * @example
59
- * ```typescript
60
- * const entry = { value: data, timestamp: Date.now() - 1000, ttl: 10000 };
61
- * if (CacheValidator.isFresh(entry)) {
62
- * console.log('Cache is fresh');
63
- * }
64
- * ```
65
- */
66
- class CacheValidator {
67
- /**
68
- * Check if a cache entry is within its TTL (fresh).
69
- *
70
- * @param entry - The cache entry to validate
71
- * @returns true if the entry is fresh, false if expired
72
- *
73
- * @example
74
- * ```typescript
75
- * if (CacheValidator.isFresh(cacheEntry)) {
76
- * return cacheEntry.value;
77
- * }
78
- * ```
79
- */
80
- static isFresh(entry) {
81
- const age = Date.now() - entry.timestamp;
82
- return age < entry.ttl;
83
- }
84
- /**
85
- * Determine if a cache entry should be considered stale (older than TTL but within revalidate window).
86
- *
87
- * @param entry - The cache entry to validate
88
- * @returns true if the entry is stale, false otherwise
89
- *
90
- * @example
91
- * ```typescript
92
- * if (CacheValidator.isStale(cacheEntry)) {
93
- * console.log('Cache is stale; revalidating...');
94
- * }
95
- * ```
96
- */
97
- static isStale(entry) {
98
- const age = Date.now() - entry.timestamp;
99
- // Stale = past TTL but still retrievable (used with staleWhileRevalidate or useStaleOnError)
100
- return age >= entry.ttl;
101
- }
102
- /**
103
- * Check if a cache entry is expired based on age (age > ttl).
104
- * Expired entries should be removed during cleanup.
105
- *
106
- * @param entry - The cache entry to validate
107
- * @returns true if the entry is expired, false otherwise
108
- *
109
- * @example
110
- * ```typescript
111
- * if (CacheValidator.isExpired(cacheEntry)) {
112
- * await cacheLayer.remove(key);
113
- * }
114
- * ```
115
- */
116
- static isExpired(entry) {
117
- const age = Date.now() - entry.timestamp;
118
- return age > entry.ttl;
119
- }
120
- /**
121
- * Get the remaining TTL for a cache entry in milliseconds.
122
- * Negative values indicate the entry is already expired.
123
- *
124
- * @param entry - The cache entry to check
125
- * @returns Milliseconds remaining until expiry (negative if expired)
126
- *
127
- * @example
128
- * ```typescript
129
- * const remaining = CacheValidator.getTimeRemaining(entry);
130
- * console.log(`Cache expires in ${remaining}ms`);
131
- * ```
132
- */
133
- static getTimeRemaining(entry) {
134
- const age = Date.now() - entry.timestamp;
135
- return entry.ttl - age;
136
- }
137
- }
138
-
139
- /**
140
- * Deep clones a value to ensure cached objects are isolated from the original.
141
- * Handles JSON-serializable types (objects, arrays, primitives).
142
- *
143
- * @param value - The value to clone
144
- * @returns A deep copy of the value
145
- *
146
- * @example
147
- * ```typescript
148
- * const config = { theme: 'dark', nested: { option: true } };
149
- * const cached = cloneValue(config);
150
- * cached.nested.option = false; // Original config is unchanged
151
- * ```
152
- */
153
- function cloneValue(value) {
154
- if (value === null || typeof value !== 'object') {
155
- return value;
156
- }
157
- if (Array.isArray(value)) {
158
- return value.map((item) => cloneValue(item));
159
- }
160
- if (value instanceof Date) {
161
- return new Date(value.getTime());
162
- }
163
- // Handle plain objects
164
- const cloned = {};
165
- for (const key in value) {
166
- if (Object.prototype.hasOwnProperty.call(value, key)) {
167
- cloned[key] = cloneValue(value[key]);
168
- }
169
- }
170
- return cloned;
171
- }
172
-
173
- /**
174
- * IndexedDB-backed cache layer implementation.
175
- * Most persistent and largest capacity (~50MB+ depending on browser).
176
- * Survives page reload and browser session; user must explicitly clear.
177
- * Async operations with transactions ensure data integrity.
178
- *
179
- * @template T The type of data stored
180
- *
181
- * @example
182
- * ```typescript
183
- * const indexedDbCache = new IndexedDbCacheLayer<Config>('my-app', 'sixbell-theme-resources');
184
- * await indexedDbCache.set('config', { theme: 'dark' }, 3600000);
185
- * const entry = await indexedDbCache.get('config');
186
- * ```
187
- */
188
- class IndexedDbCacheLayer {
189
- cacheName;
190
- databaseName;
191
- dbPromise = null;
192
- constructor(cacheName, databaseName = INDEXED_DB_NAME) {
193
- this.cacheName = cacheName;
194
- this.databaseName = databaseName;
195
- }
196
- /**
197
- * Retrieve a cached entry from IndexedDB.
198
- *
199
- * @param key - The cache key
200
- * @returns The cached entry if found and fresh, null otherwise
201
- *
202
- * @example
203
- * ```typescript
204
- * const entry = await indexedDbCache.get('theme-config');
205
- * if (entry) {
206
- * console.log('Found in IndexedDB:', entry.value);
207
- * }
208
- * ```
209
- */
210
- async get(key) {
211
- try {
212
- const db = await this.getDatabase();
213
- const tx = db.transaction([INDEXED_DB_STORE_NAME], 'readonly');
214
- const store = tx.objectStore(INDEXED_DB_STORE_NAME);
215
- const stored = await this.getFromStore(store, this.getStorageKey(key));
216
- if (!stored) {
217
- return null;
218
- }
219
- const entry = stored;
220
- if (CacheValidator.isExpired(entry)) {
221
- // Clean up expired entry in background
222
- this.remove(key).catch(() => { });
223
- return null;
224
- }
225
- // Return entry even if stale; caller decides whether to use it
226
- return entry;
227
- }
228
- catch {
229
- // Handle errors gracefully
230
- return null;
231
- }
232
- }
233
- /**
234
- * Store a value in IndexedDB.
235
- *
236
- * @param key - The cache key
237
- * @param value - The data to cache
238
- * @param ttl - Time-to-live in milliseconds
239
- *
240
- * @example
241
- * ```typescript
242
- * await indexedDbCache.set('theme', { mode: 'dark' }, 3600000);
243
- * ```
244
- */
245
- async set(key, value, ttl) {
246
- try {
247
- const db = await this.getDatabase();
248
- const tx = db.transaction([INDEXED_DB_STORE_NAME], 'readwrite');
249
- const store = tx.objectStore(INDEXED_DB_STORE_NAME);
250
- const entry = {
251
- value: cloneValue(value),
252
- timestamp: Date.now(),
253
- ttl,
254
- };
255
- await this.putInStore(store, this.getStorageKey(key), entry);
256
- }
257
- catch {
258
- // Silently fail if IndexedDB is unavailable
259
- }
260
- }
261
- /**
262
- * Remove a cached entry from IndexedDB.
263
- *
264
- * @param key - The cache key
265
- *
266
- * @example
267
- * ```typescript
268
- * await indexedDbCache.remove('theme-config');
269
- * ```
270
- */
271
- async remove(key) {
272
- try {
273
- const db = await this.getDatabase();
274
- const tx = db.transaction([INDEXED_DB_STORE_NAME], 'readwrite');
275
- const store = tx.objectStore(INDEXED_DB_STORE_NAME);
276
- await this.deleteFromStore(store, this.getStorageKey(key));
277
- }
278
- catch {
279
- // Silently fail if IndexedDB is unavailable
280
- }
281
- }
282
- /**
283
- * Clear all entries from IndexedDB with this cache name prefix.
284
- *
285
- * @example
286
- * ```typescript
287
- * await indexedDbCache.clear();
288
- * ```
289
- */
290
- async clear() {
291
- try {
292
- const db = await this.getDatabase();
293
- const tx = db.transaction([INDEXED_DB_STORE_NAME], 'readwrite');
294
- const store = tx.objectStore(INDEXED_DB_STORE_NAME);
295
- const prefix = `${this.cacheName}:`;
296
- const allKeys = await this.getAllKeysFromStore(store);
297
- const keysToDelete = allKeys.filter((k) => typeof k === 'string' && k.startsWith(prefix)).map((k) => k);
298
- await Promise.all(keysToDelete.map((k) => this.deleteFromStore(store, k)));
299
- }
300
- catch {
301
- // Silently fail if IndexedDB is unavailable
302
- }
303
- }
304
- /**
305
- * Remove all expired entries from IndexedDB.
306
- *
307
- * @example
308
- * ```typescript
309
- * await indexedDbCache.cleanup();
310
- * ```
311
- */
312
- async cleanup() {
313
- try {
314
- const db = await this.getDatabase();
315
- const tx = db.transaction([INDEXED_DB_STORE_NAME], 'readwrite');
316
- const store = tx.objectStore(INDEXED_DB_STORE_NAME);
317
- const prefix = `${this.cacheName}:`;
318
- const allKeys = await this.getAllKeysFromStore(store);
319
- const keysToDelete = [];
320
- for (const keyItem of allKeys) {
321
- const key = keyItem;
322
- if (!key.startsWith(prefix)) {
323
- continue;
324
- }
325
- const stored = await this.getFromStore(store, key);
326
- if (stored && CacheValidator.isExpired(stored)) {
327
- keysToDelete.push(key);
328
- }
329
- }
330
- await Promise.all(keysToDelete.map((k) => this.deleteFromStore(store, k)));
331
- }
332
- catch {
333
- // Silently fail if IndexedDB is unavailable
334
- }
335
- }
336
- /**
337
- * Get or create the IndexedDB database connection.
338
- *
339
- * @private
340
- * @returns Promise that resolves to the IDBDatabase instance
341
- */
342
- async getDatabase() {
343
- if (this.dbPromise) {
344
- return this.dbPromise;
345
- }
346
- this.dbPromise = new Promise((resolve, reject) => {
347
- const request = indexedDB.open(this.databaseName, 1);
348
- request.onupgradeneeded = () => {
349
- const db = request.result;
350
- if (!db.objectStoreNames.contains(INDEXED_DB_STORE_NAME)) {
351
- db.createObjectStore(INDEXED_DB_STORE_NAME);
352
- }
353
- };
354
- request.onsuccess = () => {
355
- resolve(request.result);
356
- };
357
- request.onerror = () => {
358
- reject(new Error('Failed to open IndexedDB'));
359
- };
360
- });
361
- return this.dbPromise;
362
- }
363
- /**
364
- * Get a value from an IndexedDB object store.
365
- *
366
- * @private
367
- */
368
- getFromStore(store, key) {
369
- return new Promise((resolve, reject) => {
370
- const request = store.get(key);
371
- request.onsuccess = () => {
372
- resolve(request.result || null);
373
- };
374
- request.onerror = () => {
375
- reject(new Error('Failed to get from store'));
376
- };
377
- });
378
- }
379
- /**
380
- * Put a value into an IndexedDB object store.
381
- *
382
- * @private
383
- */
384
- putInStore(store, key, value) {
385
- return new Promise((resolve, reject) => {
386
- const request = store.put(value, key);
387
- request.onsuccess = () => {
388
- resolve();
389
- };
390
- request.onerror = () => {
391
- reject(new Error('Failed to put into store'));
392
- };
393
- });
394
- }
395
- /**
396
- * Delete a value from an IndexedDB object store.
397
- *
398
- * @private
399
- */
400
- deleteFromStore(store, key) {
401
- return new Promise((resolve, reject) => {
402
- const request = store.delete(key);
403
- request.onsuccess = () => {
404
- resolve();
405
- };
406
- request.onerror = () => {
407
- reject(new Error('Failed to delete from store'));
408
- };
409
- });
410
- }
411
- /**
412
- * Get all keys from an IndexedDB object store.
413
- *
414
- * @private
415
- */
416
- getAllKeysFromStore(store) {
417
- return new Promise((resolve, reject) => {
418
- const request = store.getAllKeys();
419
- request.onsuccess = () => {
420
- resolve(request.result);
421
- };
422
- request.onerror = () => {
423
- reject(new Error('Failed to get all keys from store'));
424
- };
425
- });
426
- }
427
- /**
428
- * Get the full storage key with namespace prefix.
429
- *
430
- * @private
431
- * @param key - The logical cache key
432
- * @returns The full storage key with prefix
433
- */
434
- getStorageKey(key) {
435
- return `${this.cacheName}:${key}`;
436
- }
437
- }
438
-
439
- /**
440
- * localStorage-backed cache layer implementation.
441
- * Persistent across page reloads and browser sessions (capacity ~5-10MB per domain).
442
- * Falls back gracefully if localStorage is unavailable (private browsing, quota exceeded).
443
- *
444
- * Stores entries as JSON strings with a namespace prefix to avoid collisions.
445
- *
446
- * @template T The type of data stored
447
- *
448
- * @example
449
- * ```typescript
450
- * const localCache = new LocalStorageCacheLayer<Config>('my-app');
451
- * await localCache.set('config', { theme: 'dark' }, 3600000);
452
- * const entry = await localCache.get('config');
453
- * ```
454
- */
455
- class LocalStorageCacheLayer {
456
- cacheName;
457
- constructor(cacheName) {
458
- this.cacheName = cacheName;
459
- }
460
- /**
461
- * Retrieve a cached entry from localStorage.
462
- *
463
- * @param key - The cache key
464
- * @returns The cached entry if found and fresh, null otherwise
465
- *
466
- * @example
467
- * ```typescript
468
- * const entry = await localCache.get('theme-config');
469
- * if (entry) {
470
- * console.log('Found in localStorage:', entry.value);
471
- * }
472
- * ```
473
- */
474
- async get(key) {
475
- try {
476
- const stored = localStorage.getItem(this.getStorageKey(key));
477
- if (!stored) {
478
- return null;
479
- }
480
- const entry = JSON.parse(stored);
481
- if (CacheValidator.isExpired(entry)) {
482
- // Clean up expired entry
483
- localStorage.removeItem(this.getStorageKey(key));
484
- return null;
485
- }
486
- // Return entry even if stale; caller decides whether to use it
487
- return entry;
488
- }
489
- catch {
490
- // Handle parsing errors or localStorage access issues
491
- return null;
492
- }
493
- }
494
- /**
495
- * Store a value in localStorage.
496
- *
497
- * @param key - The cache key
498
- * @param value - The data to cache
499
- * @param ttl - Time-to-live in milliseconds
500
- *
501
- * @example
502
- * ```typescript
503
- * await localCache.set('theme', { mode: 'dark' }, 3600000);
504
- * ```
505
- */
506
- async set(key, value, ttl) {
507
- try {
508
- const entry = {
509
- value: cloneValue(value),
510
- timestamp: Date.now(),
511
- ttl,
512
- };
513
- localStorage.setItem(this.getStorageKey(key), JSON.stringify(entry));
514
- }
515
- catch {
516
- // Silently fail on quota exceeded or access denied
517
- // (e.g., private browsing mode, storage quota exceeded)
518
- }
519
- }
520
- /**
521
- * Remove a cached entry from localStorage.
522
- *
523
- * @param key - The cache key
524
- *
525
- * @example
526
- * ```typescript
527
- * await localCache.remove('theme-config');
528
- * ```
529
- */
530
- async remove(key) {
531
- try {
532
- localStorage.removeItem(this.getStorageKey(key));
533
- }
534
- catch {
535
- // Silently fail if localStorage is unavailable
536
- }
537
- }
538
- /**
539
- * Clear all entries from localStorage with this cache name prefix.
540
- *
541
- * @example
542
- * ```typescript
543
- * await localCache.clear();
544
- * ```
545
- */
546
- async clear() {
547
- try {
548
- const prefix = `${this.cacheName}:`;
549
- const keysToDelete = [];
550
- for (let i = 0; i < localStorage.length; i++) {
551
- const key = localStorage.key(i);
552
- if (key?.startsWith(prefix)) {
553
- keysToDelete.push(key);
554
- }
555
- }
556
- keysToDelete.forEach((key) => localStorage.removeItem(key));
557
- }
558
- catch {
559
- // Silently fail if localStorage is unavailable
560
- }
561
- }
562
- /**
563
- * Remove all expired entries from localStorage.
564
- *
565
- * @example
566
- * ```typescript
567
- * await localCache.cleanup();
568
- * ```
569
- */
570
- async cleanup() {
571
- try {
572
- const prefix = `${this.cacheName}:`;
573
- const keysToDelete = [];
574
- for (let i = 0; i < localStorage.length; i++) {
575
- const key = localStorage.key(i);
576
- if (!key?.startsWith(prefix)) {
577
- continue;
578
- }
579
- const stored = localStorage.getItem(key);
580
- if (!stored) {
581
- continue;
582
- }
583
- try {
584
- const entry = JSON.parse(stored);
585
- if (CacheValidator.isExpired(entry)) {
586
- keysToDelete.push(key);
587
- }
588
- }
589
- catch {
590
- // Skip unparseable entries
591
- }
592
- }
593
- keysToDelete.forEach((key) => localStorage.removeItem(key));
594
- }
595
- catch {
596
- // Silently fail if localStorage is unavailable
597
- }
598
- }
599
- /**
600
- * Get the full storage key with namespace prefix.
601
- *
602
- * @private
603
- * @param key - The logical cache key
604
- * @returns The full storage key with prefix
605
- */
606
- getStorageKey(key) {
607
- return `${this.cacheName}:${key}`;
608
- }
609
- }
610
-
611
- /**
612
- * In-memory cache layer implementation.
613
- * Fastest but volatile—cleared on page reload and browser session close.
614
- *
615
- * Uses a Map to store entries with O(1) lookup and retrieval.
616
- *
617
- * @template T The type of data stored
618
- *
619
- * @example
620
- * ```typescript
621
- * const memoryCache = new MemoryCacheLayer<Config>();
622
- * await memoryCache.set('config', { theme: 'dark' }, 3600000);
623
- * const entry = await memoryCache.get('config');
624
- * ```
625
- */
626
- class MemoryCacheLayer {
627
- store = new Map();
628
- /**
629
- * Retrieve a cached entry from memory.
630
- *
631
- * @param key - The cache key
632
- * @returns The cached entry if found and fresh, null otherwise
633
- *
634
- * @example
635
- * ```typescript
636
- * const entry = await memoryCache.get('theme-config');
637
- * if (entry) {
638
- * console.log('Found in memory:', entry.value);
639
- * }
640
- * ```
641
- */
642
- async get(key) {
643
- const entry = this.store.get(key);
644
- if (!entry) {
645
- return null;
646
- }
647
- // Return entry even if stale; caller decides whether to use it
648
- if (CacheValidator.isExpired(entry)) {
649
- // Clean up expired entry
650
- this.store.delete(key);
651
- return null;
652
- }
653
- return entry;
654
- }
655
- /**
656
- * Store a value in memory cache.
657
- *
658
- * @param key - The cache key
659
- * @param value - The data to cache
660
- * @param ttl - Time-to-live in milliseconds
661
- *
662
- * @example
663
- * ```typescript
664
- * await memoryCache.set('theme', { mode: 'dark' }, 3600000);
665
- * ```
666
- */
667
- async set(key, value, ttl) {
668
- this.store.set(key, {
669
- value,
670
- timestamp: Date.now(),
671
- ttl,
672
- });
673
- }
674
- /**
675
- * Remove a cached entry from memory.
676
- *
677
- * @param key - The cache key
678
- *
679
- * @example
680
- * ```typescript
681
- * await memoryCache.remove('theme-config');
682
- * ```
683
- */
684
- async remove(key) {
685
- this.store.delete(key);
686
- }
687
- /**
688
- * Clear all entries from memory cache.
689
- *
690
- * @example
691
- * ```typescript
692
- * await memoryCache.clear();
693
- * ```
694
- */
695
- async clear() {
696
- this.store.clear();
697
- }
698
- /**
699
- * Remove all expired entries from memory cache.
700
- *
701
- * @example
702
- * ```typescript
703
- * await memoryCache.cleanup();
704
- * ```
705
- */
706
- async cleanup() {
707
- const keysToDelete = [];
708
- for (const [key, entry] of this.store.entries()) {
709
- if (CacheValidator.isExpired(entry)) {
710
- keysToDelete.push(key);
711
- }
712
- }
713
- keysToDelete.forEach((key) => this.store.delete(key));
714
- }
715
- }
716
-
717
- /**
718
- * Factory for creating cache layer instances based on layer name.
719
- * Decouples cache layer creation from usage throughout the application.
720
- * Makes it easy to swap or customize cache backends.
721
- *
722
- * @example
723
- * ```typescript
724
- * const cacheLayer = CacheLayerFactory.create({
725
- * layerName: 'indexedDB',
726
- * cacheName: 'my-app-cache'
727
- * });
728
- *
729
- * // All three layer types can be created the same way
730
- * const memory = CacheLayerFactory.create({ layerName: 'memory', cacheName: 'app' });
731
- * const local = CacheLayerFactory.create({ layerName: 'localStorage', cacheName: 'app' });
732
- * const idb = CacheLayerFactory.create({ layerName: 'indexedDB', cacheName: 'app' });
733
- * ```
734
- */
735
- class CacheLayerFactory {
736
- /**
737
- * Create a cache layer instance based on the specified layer name.
738
- *
739
- * @param options - Factory options including layer name and cache name
740
- * @returns A new cache layer instance
741
- *
742
- * @throws Error if the layer name is not recognized
743
- *
744
- * @example
745
- * ```typescript
746
- * const layer = CacheLayerFactory.create({
747
- * layerName: 'indexedDB',
748
- * cacheName: 'themes'
749
- * });
750
- * ```
751
- */
752
- static create(options) {
753
- const { layerName, cacheName, indexedDBName } = options;
754
- switch (layerName) {
755
- case 'indexedDB':
756
- return new IndexedDbCacheLayer(cacheName, indexedDBName);
757
- case 'localStorage':
758
- return new LocalStorageCacheLayer(cacheName);
759
- case 'memory':
760
- return new MemoryCacheLayer();
761
- default:
762
- const exhaustive = layerName;
763
- throw new Error(`Unknown cache layer: ${exhaustive}`);
764
- }
765
- }
766
- }
767
-
768
- /**
769
- * Merges global defaults with per-request options into a single configuration object.
770
- * Eliminates scattered config assignments throughout the codebase.
771
- *
772
- * @template T The expected data type
773
- *
774
- * @example
775
- * ```typescript
776
- * const config = new LoadConfig<MyData>(defaults, requestOptions);
777
- * console.log(config.cacheTTL); // Value from requestOptions or defaults
778
- * console.log(config.retries); // Value from requestOptions or defaults
779
- * ```
780
- */
781
- class LoadConfig {
782
- cacheName;
783
- storageOrder;
784
- cacheTTL;
785
- staleWhileRevalidate;
786
- useStaleOnError;
787
- revalidateOnFresh;
788
- retries;
789
- retryDelayMs;
790
- timeoutMs;
791
- parser;
792
- seedCacheWithFallback;
793
- logErrors;
794
- freshOnNavigation;
795
- cacheKey;
796
- fallbackData;
797
- constructor(defaults, options, url) {
798
- // Merge defaults and options, with options taking precedence
799
- const merged = { ...RESOURCE_LOADER_DEFAULTS, ...defaults, ...options };
800
- this.cacheName = merged.cacheName ?? RESOURCE_LOADER_DEFAULTS.cacheName;
801
- this.storageOrder = merged.storageOrder ?? RESOURCE_LOADER_DEFAULTS.storageOrder;
802
- this.cacheTTL = merged.cacheTTL ?? RESOURCE_LOADER_DEFAULTS.cacheTTL;
803
- this.staleWhileRevalidate = merged.staleWhileRevalidate ?? RESOURCE_LOADER_DEFAULTS.staleWhileRevalidate;
804
- this.useStaleOnError = merged.useStaleOnError ?? RESOURCE_LOADER_DEFAULTS.useStaleOnError;
805
- this.revalidateOnFresh = merged.revalidateOnFresh ?? RESOURCE_LOADER_DEFAULTS.revalidateOnFresh;
806
- this.retries = Math.min(merged.retries ?? RESOURCE_LOADER_DEFAULTS.retries, 5);
807
- this.retryDelayMs = merged.retryDelayMs ?? RESOURCE_LOADER_DEFAULTS.retryDelayMs;
808
- this.timeoutMs = merged.timeoutMs ?? RESOURCE_LOADER_DEFAULTS.timeoutMs;
809
- this.parser = merged.parser ?? ((response) => response.json());
810
- this.seedCacheWithFallback = merged.seedCacheWithFallback ?? RESOURCE_LOADER_DEFAULTS.seedCacheWithFallback;
811
- this.logErrors = merged.logErrors ?? RESOURCE_LOADER_DEFAULTS.logErrors;
812
- this.freshOnNavigation = merged.freshOnNavigation ?? RESOURCE_LOADER_DEFAULTS.freshOnNavigation;
813
- this.cacheKey = merged.cacheKey ?? url;
814
- this.fallbackData = merged.fallbackData;
815
- }
816
- }
817
-
818
- /**
819
- * Encapsulates HTTP request logic with built-in retry and timeout support.
820
- * Centralizes fetch implementation to eliminate duplication across the codebase.
821
- *
822
- * @example
823
- * ```typescript
824
- * const client = new RetryableHttpClient(3, 250, 8000);
825
- * const response = await client.fetch('https://example.com/data');
826
- * ```
827
- */
828
- class RetryableHttpClient {
829
- retries;
830
- retryDelayMs;
831
- timeoutMs;
832
- constructor(retries, retryDelayMs, timeoutMs) {
833
- this.retries = retries;
834
- this.retryDelayMs = retryDelayMs;
835
- this.timeoutMs = timeoutMs;
836
- }
837
- /**
838
- * Fetch a resource with automatic retry and timeout support.
839
- *
840
- * @param url - The resource URL
841
- * @returns The Response object
842
- * @throws Error if all retries are exhausted or fetch fails
843
- *
844
- * @example
845
- * ```typescript
846
- * try {
847
- * const response = await client.fetch('https://api.example.com/config');
848
- * const data = await response.json();
849
- * } catch (error) {
850
- * console.error('Failed to fetch:', error);
851
- * }
852
- * ```
853
- */
854
- async fetch(url) {
855
- let lastError = null;
856
- // Total attempts = retries + 1 (initial attempt)
857
- for (let attempt = 0; attempt <= this.retries; attempt++) {
858
- try {
859
- return await this.attemptFetch(url);
860
- }
861
- catch (error) {
862
- lastError = error instanceof Error ? error : new Error(String(error));
863
- // Don't delay on last attempt
864
- if (attempt < this.retries) {
865
- await new Promise((resolve) => setTimeout(resolve, this.retryDelayMs));
866
- }
867
- }
868
- }
869
- throw lastError || new Error('Failed to fetch after retries');
870
- }
871
- /**
872
- * Single fetch attempt with timeout.
873
- *
874
- * @private
875
- * @param url - The resource URL
876
- * @returns The Response object
877
- * @throws Error if fetch times out or fails
878
- */
879
- async attemptFetch(url) {
880
- const controller = new AbortController();
881
- const timeoutHandle = setTimeout(() => controller.abort(), this.timeoutMs);
882
- try {
883
- const response = await fetch(url, { signal: controller.signal });
884
- if (!response.ok) {
885
- throw new Error(`HTTP ${response.status}: ${response.statusText}`);
886
- }
887
- return response;
888
- }
889
- finally {
890
- clearTimeout(timeoutHandle);
891
- }
892
- }
893
- }
894
-
895
- /**
896
- * Provides intelligent resource loading with:
897
- * - **Multi-layer caching**: IndexedDB (persistent) → localStorage → memory, with automatic fallback
898
- * - **Retry logic**: Configurable retries with exponential backoff and request timeouts
899
- * - **Stale-while-revalidate**: Serve cached data immediately, refresh in background
900
- * - **Fallback support**: Gracefully degrade to fallback data when all else fails
901
- * - **Request deduplication**: Multiple identical requests share a single network call
902
- *
903
- * @example Basic usage (theme configuration):
904
- * ```typescript
905
- * const loader = new ResourceLoader({
906
- * cacheName: 'theme-cache',
907
- * cacheTTL: 1000 * 60 * 60 * 24, // 24 hours
908
- * storageOrder: ['indexedDB', 'localStorage', 'memory'],
909
- * });
910
- *
911
- * const result = await loader.load<ThemeConfig>('assets/themes/config.json', {
912
- * fallbackData: DEFAULT_THEME_CONFIG,
913
- * parser: async (response) => (await response.json()) as ThemeConfig,
914
- * });
915
- *
916
- * console.log(result.data); // Theme configuration
917
- * console.log(result.source); // 'cache', 'network', or 'fallback'
918
- * console.log(result.cacheStatus); // 'fresh', 'stale', or 'miss'
919
- * ```
920
- */
921
- class ResourceLoader {
922
- defaults;
923
- layerPool = new Map();
924
- inFlightLoads = new Map();
925
- logger;
926
- indexedDBName;
927
- /**
928
- * Creates a new ResourceLoader instance.
929
- *
930
- * @param defaults Global default configuration applied to all load operations
931
- * @param logger Optional logger instance for debug output
932
- */
933
- constructor(defaults = {}, logger) {
934
- this.defaults = defaults;
935
- this.logger = logger || new LoggerService();
936
- this.indexedDBName = defaults.indexedDBName || INDEXED_DB_NAME;
937
- }
938
- /**
939
- * Loads a resource with intelligent caching, retry, and fallback support.
940
- *
941
- * @template T The expected data type to be loaded
942
- * @param url The URL or path to fetch the resource from
943
- * @param options Request-specific options (override defaults)
944
- * @returns A promise resolving to a ResourceLoadResult containing data, source, and cache status
945
- */
946
- load(url, options) {
947
- const mergedOptions = options ?? {};
948
- const cacheKey = mergedOptions.cacheKey ?? this.defaults.defaultCacheKey ?? url;
949
- const existing = this.inFlightLoads.get(cacheKey);
950
- if (existing) {
951
- this.logger.debug('Deduplicating in-flight load', {
952
- component: 'ResourceLoader',
953
- action: 'load',
954
- cacheKey,
955
- });
956
- return existing;
957
- }
958
- this.logger.debug('Starting load', {
959
- component: 'ResourceLoader',
960
- action: 'load',
961
- cacheKey,
962
- });
963
- const promise = this.loadInternal(url, cacheKey, mergedOptions)
964
- .finally(() => {
965
- this.inFlightLoads.delete(cacheKey);
966
- })
967
- .catch((error) => {
968
- this.inFlightLoads.delete(cacheKey);
969
- throw error;
970
- });
971
- this.inFlightLoads.set(cacheKey, promise);
972
- return promise;
973
- }
974
- async loadInternal(url, cacheKey, options) {
975
- const config = new LoadConfig(this.defaults, options, url);
976
- this.logger.debug('Load config created', {
977
- component: 'ResourceLoader',
978
- action: 'loadInternal',
979
- cacheKey,
980
- cacheName: config.cacheName,
981
- freshOnNavigation: config.freshOnNavigation,
982
- });
983
- const layers = this.buildLayers(config.cacheName, config.storageOrder);
984
- const httpClient = new RetryableHttpClient(config.retries, config.retryDelayMs, config.timeoutMs);
985
- const now = Date.now();
986
- // Step 1: Attempt cache lookup (if not in freshOnNavigation mode)
987
- const cacheState = await this.lookupCache(cacheKey, layers, config.freshOnNavigation);
988
- const isFresh = cacheState.entry ? CacheValidator.isFresh(cacheState.entry) : false;
989
- this.logCacheStatus(cacheKey, cacheState.entry, isFresh);
990
- // Step 2: Handle fresh cache hits with optional revalidation
991
- if (cacheState.entry && isFresh && !config.revalidateOnFresh) {
992
- return this.returnCacheResult(cacheState.entry, 'fresh');
993
- }
994
- if (cacheState.entry && isFresh && config.revalidateOnFresh) {
995
- return this.returnCacheWithRevalidation(cacheState.entry, url, cacheKey, layers, config, httpClient, 'fresh');
996
- }
997
- // Step 3: Handle stale cache with revalidation
998
- if (cacheState.entry && !isFresh && config.staleWhileRevalidate) {
999
- return this.returnCacheWithRevalidation(cacheState.entry, url, cacheKey, layers, config, httpClient, 'stale');
1000
- }
1001
- // Step 4: Fetch from network
1002
- return this.fetchAndHandleError(url, cacheKey, layers, config, httpClient, cacheState.entry, now, options.fallbackData);
1003
- }
1004
- async lookupCache(cacheKey, layers, skipLookup) {
1005
- if (skipLookup) {
1006
- this.logger.debug('Skipping cache check (freshOnNavigation enabled)', {
1007
- component: 'ResourceLoader',
1008
- action: 'lookupCache',
1009
- cacheKey,
1010
- });
1011
- return { entry: undefined, layerUsed: undefined };
1012
- }
1013
- this.logger.debug('Checking cache layers', {
1014
- component: 'ResourceLoader',
1015
- action: 'lookupCache',
1016
- cacheKey,
1017
- layerCount: layers.length,
1018
- });
1019
- let entry;
1020
- let layerUsed;
1021
- for (const layer of layers) {
1022
- entry = (await layer.get(cacheKey));
1023
- if (entry) {
1024
- this.logger.debug('Found cache entry in layer', {
1025
- component: 'ResourceLoader',
1026
- action: 'lookupCache',
1027
- cacheKey,
1028
- layer: layer.constructor.name,
1029
- });
1030
- layerUsed = layer;
1031
- break;
1032
- }
1033
- }
1034
- // Synchronize to other layers if found
1035
- if (entry && layerUsed) {
1036
- const otherLayers = layers.filter((layer) => layer !== layerUsed);
1037
- this.logger.debug('Synchronizing cache to other layers', {
1038
- component: 'ResourceLoader',
1039
- action: 'lookupCache',
1040
- cacheKey,
1041
- targetLayers: otherLayers.length,
1042
- });
1043
- await this.writeToLayers(cacheKey, entry, otherLayers, 0);
1044
- }
1045
- return { entry: entry || undefined, layerUsed };
1046
- }
1047
- logCacheStatus(cacheKey, entry, isFresh) {
1048
- const age = entry ? Date.now() - entry.timestamp : 'N/A';
1049
- this.logger.debug('Cache status evaluated', {
1050
- component: 'ResourceLoader',
1051
- action: 'logCacheStatus',
1052
- cacheKey,
1053
- exists: !!entry,
1054
- fresh: isFresh,
1055
- ageMs: age,
1056
- });
1057
- }
1058
- returnCacheResult(entry, status) {
1059
- this.logger.debug('Returning cache result', {
1060
- component: 'ResourceLoader',
1061
- action: 'returnCacheResult',
1062
- status,
1063
- });
1064
- return {
1065
- data: cloneValue(entry.value),
1066
- source: 'cache',
1067
- cacheStatus: status,
1068
- };
1069
- }
1070
- returnCacheWithRevalidation(entry, url, cacheKey, layers, config, httpClient, status) {
1071
- this.logger.debug('Returning cache with background revalidation', {
1072
- component: 'ResourceLoader',
1073
- action: 'returnCacheWithRevalidation',
1074
- cacheKey,
1075
- status,
1076
- });
1077
- const result = {
1078
- data: cloneValue(entry.value),
1079
- source: 'cache',
1080
- cacheStatus: status,
1081
- };
1082
- result.revalidate = this.performBackgroundRefresh(url, cacheKey, layers, config, httpClient);
1083
- return result;
1084
- }
1085
- async performBackgroundRefresh(url, cacheKey, layers, config, httpClient) {
1086
- try {
1087
- await this.performFetch(url, cacheKey, layers, config, httpClient);
1088
- this.logger.debug('Background refresh complete', {
1089
- component: 'ResourceLoader',
1090
- action: 'performBackgroundRefresh',
1091
- cacheKey,
1092
- });
1093
- }
1094
- catch (error) {
1095
- if (config.useStaleOnError) {
1096
- if (config.logErrors) {
1097
- const errorMsg = error instanceof Error ? error.message : String(error);
1098
- this.logger.warn('Using stale cache due to refresh error', {
1099
- component: 'ResourceLoader',
1100
- action: 'performBackgroundRefresh',
1101
- cacheKey,
1102
- error: errorMsg,
1103
- });
1104
- }
1105
- return;
1106
- }
1107
- throw error;
1108
- }
1109
- }
1110
- async fetchAndHandleError(url, cacheKey, layers, config, httpClient, cacheEntry, now, fallbackData) {
1111
- this.logger.debug('Fetching from network', {
1112
- component: 'ResourceLoader',
1113
- action: 'fetchAndHandleError',
1114
- cacheKey,
1115
- url,
1116
- });
1117
- try {
1118
- const data = await this.performFetch(url, cacheKey, layers, config, httpClient);
1119
- this.logger.debug('Network fetch successful', {
1120
- component: 'ResourceLoader',
1121
- action: 'fetchAndHandleError',
1122
- cacheKey,
1123
- });
1124
- return {
1125
- data,
1126
- source: 'network',
1127
- cacheStatus: cacheEntry ? 'fresh' : 'miss',
1128
- };
1129
- }
1130
- catch (error) {
1131
- this.logger.debug('Network fetch failed', {
1132
- component: 'ResourceLoader',
1133
- action: 'fetchAndHandleError',
1134
- cacheKey,
1135
- error: error instanceof Error ? error.message : String(error),
1136
- });
1137
- // Try stale cache
1138
- if (cacheEntry && config.useStaleOnError) {
1139
- this.logger.debug('Returning stale cache after fetch failure', {
1140
- component: 'ResourceLoader',
1141
- action: 'fetchAndHandleError',
1142
- cacheKey,
1143
- });
1144
- return {
1145
- data: cloneValue(cacheEntry.value),
1146
- source: 'cache',
1147
- cacheStatus: 'stale',
1148
- };
1149
- }
1150
- // Try fallback
1151
- if (fallbackData !== undefined) {
1152
- this.logger.debug('Using fallback data', {
1153
- component: 'ResourceLoader',
1154
- action: 'fetchAndHandleError',
1155
- cacheKey,
1156
- });
1157
- if (config.seedCacheWithFallback && !cacheEntry) {
1158
- this.logger.debug('Seeding cache with fallback data', {
1159
- component: 'ResourceLoader',
1160
- action: 'fetchAndHandleError',
1161
- cacheKey,
1162
- });
1163
- const fallbackEntry = {
1164
- value: cloneValue(fallbackData),
1165
- timestamp: now,
1166
- ttl: config.cacheTTL,
1167
- };
1168
- await this.writeToLayers(cacheKey, fallbackEntry, layers, config.cacheTTL);
1169
- }
1170
- return {
1171
- data: cloneValue(fallbackData),
1172
- source: 'fallback',
1173
- cacheStatus: cacheEntry ? 'stale' : 'miss',
1174
- };
1175
- }
1176
- throw error;
1177
- }
1178
- }
1179
- async performFetch(url, cacheKey, layers, config, httpClient) {
1180
- const data = await httpClient.fetch(url);
1181
- const parsed = (await config.parser(data));
1182
- const entry = {
1183
- value: cloneValue(parsed),
1184
- timestamp: Date.now(),
1185
- ttl: config.cacheTTL,
1186
- };
1187
- await this.writeToLayers(cacheKey, entry, layers, config.cacheTTL);
1188
- return parsed;
1189
- }
1190
- buildLayers(cacheName, order) {
1191
- if (!this.layerPool.has(cacheName)) {
1192
- this.layerPool.set(cacheName, new Map());
1193
- }
1194
- const cacheLayers = this.layerPool.get(cacheName);
1195
- const layers = [];
1196
- for (const name of order) {
1197
- let layer = cacheLayers.get(name);
1198
- if (!layer) {
1199
- layer = CacheLayerFactory.create({ layerName: name, cacheName, indexedDBName: this.indexedDBName });
1200
- if (layer) {
1201
- cacheLayers.set(name, layer);
1202
- }
1203
- }
1204
- if (layer) {
1205
- layers.push(layer);
1206
- }
1207
- }
1208
- return layers;
1209
- }
1210
- async writeToLayers(key, entry, layers, cacheTTL) {
1211
- await Promise.all(layers.map(async (layer) => {
1212
- await layer.set(key, cloneValue(entry.value), entry.ttl || cacheTTL);
1213
- }));
1214
- }
1215
- }
1216
-
1217
- /**
1218
- * Generated bundle index. Do not edit.
1219
- */
1220
-
1221
- export { CacheLayerFactory, CacheValidator, DEFAULT_CACHE_TTL, DEFAULT_STORAGE_ORDER, IndexedDbCacheLayer, LocalStorageCacheLayer, MemoryCacheLayer, RESOURCE_LOADER_DEFAULTS, ResourceLoader, cloneValue };
1222
- //# sourceMappingURL=sixbell-telco-sdk-utils-resource-loader.mjs.map