@kivacore/app-utils 0.0.0 → 0.22.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 (41) hide show
  1. package/README.md +1515 -1
  2. package/dist/index.d.ts +82 -0
  3. package/dist/index.js +2304 -0
  4. package/dist/index.js.map +1 -0
  5. package/dist/index.native.js +4695 -0
  6. package/dist/index.native.js.map +1 -0
  7. package/dist/query.d.ts +54 -0
  8. package/dist/query.js +269 -0
  9. package/dist/query.js.map +1 -0
  10. package/dist/types-GNkXRpu4.d.ts +754 -0
  11. package/package.json +57 -3
  12. package/src/app-config-client.ts +48 -0
  13. package/src/async-each-helper.ts +98 -0
  14. package/src/brand-client.ts +80 -0
  15. package/src/data-form-client.ts +85 -0
  16. package/src/data-source-client.ts +298 -0
  17. package/src/data-source-queries.ts +149 -0
  18. package/src/data-view-client.ts +92 -0
  19. package/src/date-utils.test.ts +48 -0
  20. package/src/date-utils.ts +146 -0
  21. package/src/envelope-interceptor.ts +65 -0
  22. package/src/get-tenant-preferences.test.ts +42 -0
  23. package/src/get-tenant-preferences.ts +30 -0
  24. package/src/handlebars-async-helpers.d.ts +12 -0
  25. package/src/index.native.ts +9 -0
  26. package/src/index.ts +88 -0
  27. package/src/inventory-client.ts +725 -0
  28. package/src/jsonata-helpers.ts +545 -0
  29. package/src/number-utils.ts +305 -0
  30. package/src/php-date-formatter.d.ts +8 -0
  31. package/src/query.ts +5 -0
  32. package/src/shims/stream.ts +11 -0
  33. package/src/template-engine.test.ts +47 -0
  34. package/src/template-engine.ts +298 -0
  35. package/src/types.ts +871 -0
  36. package/src/unwrap-envelope.ts +51 -0
  37. package/src/user-app-config-client.ts +44 -0
  38. package/src/user-identity-client.ts +21 -0
  39. package/tsconfig.json +9 -0
  40. package/tsup.config.ts +71 -0
  41. package/vitest.config.mts +13 -0
@@ -0,0 +1,725 @@
1
+ import { type RestApiClient } from '@kivacore/api-client';
2
+
3
+ import {
4
+ type AppConfig,
5
+ type Brand,
6
+ type DataForm,
7
+ type DataSource,
8
+ type DataSourceApp,
9
+ type DataView,
10
+ type InventoryClient,
11
+ type InventoryClientOptions,
12
+ type InventoryLoadOptions,
13
+ type InventoryLoadResult,
14
+ type InventoryLoadStepId,
15
+ type InventoryStorage,
16
+ type InventoryStorageOption,
17
+ type ListInventoryParams,
18
+ type TenantPreferences,
19
+ type User,
20
+ type UserAppConfig
21
+ } from './types';
22
+ import { unwrapEnvelope } from './unwrap-envelope';
23
+
24
+ const DEFAULT_TTL_MS = 5 * 60 * 1000;
25
+ const DEFAULT_DATA_SOURCES_EXPAND = 'views,forms,fields';
26
+ const DEFAULT_STORAGE_KEY = 'docyrus:inventory';
27
+ /** Bumped whenever the persisted snapshot shape changes; older snapshots are ignored. */
28
+ const SNAPSHOT_VERSION = 1;
29
+ const DEFAULT_LOAD_STEPS: InventoryLoadStepId[] = [
30
+ 'apps',
31
+ 'data-sources',
32
+ 'users',
33
+ 'brands',
34
+ 'preferences'
35
+ ];
36
+
37
+ interface CacheEntry<T> {
38
+ data: T;
39
+ fetchedAt: number;
40
+ }
41
+
42
+ interface InventorySnapshot {
43
+ v: number;
44
+ apps: CacheEntry<DataSourceApp[]> | null;
45
+ dataSources: CacheEntry<DataSource[]> | null;
46
+ users: CacheEntry<User[]> | null;
47
+ brands: CacheEntry<Brand[]> | null;
48
+ preferences: CacheEntry<TenantPreferences> | null;
49
+ appConfigs: Array<[string, CacheEntry<AppConfig | null>]>;
50
+ userAppConfigs: Array<[string, CacheEntry<UserAppConfig | null>]>;
51
+ }
52
+
53
+ /**
54
+ * Resolve a `storage` option into an `InventoryStorage`, or `null` when
55
+ * persistence is off or unavailable. String options map to the Web Storage
56
+ * globals; a probe write/remove confirms the store is actually usable (private
57
+ * mode and disabled cookies expose the object but throw on access). Any failure
58
+ * degrades gracefully to in-memory — this never throws.
59
+ */
60
+ function resolveStorage(option: InventoryStorageOption | undefined): InventoryStorage | null {
61
+ if (!option) return null;
62
+ if (typeof option !== 'string') return option;
63
+
64
+ try {
65
+ const key = option === 'session' ? 'sessionStorage' : 'localStorage';
66
+ const store = (globalThis as unknown as Record<string, InventoryStorage | undefined>)[key];
67
+
68
+ if (!store) return null;
69
+
70
+ const probe = '__docyrus_inventory_probe__';
71
+
72
+ store.setItem(probe, probe);
73
+ store.removeItem(probe);
74
+
75
+ return store;
76
+ } catch {
77
+ return null;
78
+ }
79
+ }
80
+
81
+ function toIdSet(value?: string | string[]): Set<string> | null {
82
+ if (value === undefined) return null;
83
+
84
+ return new Set(Array.isArray(value) ? value : [value]);
85
+ }
86
+
87
+ function isNotFound(error: unknown): boolean {
88
+ return typeof error === 'object' && error !== null && (error as { status?: number }).status === 404;
89
+ }
90
+
91
+ /**
92
+ * Reads the current app id from `VITE_APP_ID`, checking both Vite's
93
+ * `import.meta.env` and Node's `process.env` so it works in browser bundles
94
+ * and SSR / tooling alike. Returns `undefined` when unset or empty.
95
+ */
96
+ function readAppIdFromEnv(): string | undefined {
97
+ let value: string | undefined;
98
+
99
+ try {
100
+ value = (import.meta as unknown as { env?: Record<string, string | undefined> }).env?.VITE_APP_ID;
101
+ } catch {
102
+ value = undefined;
103
+ }
104
+
105
+ if (!value && typeof process !== 'undefined') {
106
+ value = process.env?.VITE_APP_ID;
107
+ }
108
+
109
+ return value && value.length > 0 ? value : undefined;
110
+ }
111
+
112
+ /**
113
+ * Normalize an embedded form into the canonical `DataForm` shape:
114
+ * - the embedded payload is camelCased (`isDefault` instead of `is_default`)
115
+ * - it omits `tenant_data_source_id`, `archived`, and the audit timestamps
116
+ *
117
+ * Standalone-API forms are already in canonical shape, so this is idempotent
118
+ * for them.
119
+ */
120
+ function normalizeEmbeddedForm(raw: Record<string, unknown>, dataSourceId: string): DataForm {
121
+ const isDefault = (raw.is_default ?? raw.isDefault ?? false) as boolean;
122
+ const tenantDataSourceId = (raw.tenant_data_source_id ?? dataSourceId) as string;
123
+
124
+ return {
125
+ ...(raw as unknown as DataForm),
126
+ tenant_data_source_id: tenantDataSourceId,
127
+ is_default: isDefault,
128
+ archived: (raw.archived as boolean | undefined) ?? false
129
+ };
130
+ }
131
+
132
+ /**
133
+ * Embedded views are full `DataView` objects minus the `archived` field
134
+ * (archived rows are filtered server-side). Fill it in so consumers see a
135
+ * stable shape regardless of fetch origin.
136
+ */
137
+ function normalizeEmbeddedView(raw: DataView): DataView {
138
+ return raw.archived === undefined ? { ...raw, archived: false } : raw;
139
+ }
140
+
141
+ function normalizeDataSource(dataSource: DataSource): DataSource {
142
+ const views = Array.isArray(dataSource.views) ? dataSource.views.map(normalizeEmbeddedView) : dataSource.views;
143
+ const forms = Array.isArray(dataSource.forms) ? (dataSource.forms as unknown as Array<Record<string, unknown>>).map(form => normalizeEmbeddedForm(form, dataSource.id)) : dataSource.forms;
144
+
145
+ if (views === dataSource.views && forms === dataSource.forms) return dataSource;
146
+
147
+ return { ...dataSource, views, forms };
148
+ }
149
+
150
+ export function createInventoryClient(
151
+ client: RestApiClient,
152
+ options?: InventoryClientOptions
153
+ ): InventoryClient {
154
+ const ttlMs = options?.ttlMs ?? DEFAULT_TTL_MS;
155
+ const dataSourcesExpand = options?.dataSourcesExpand ?? DEFAULT_DATA_SOURCES_EXPAND;
156
+ const storage = resolveStorage(options?.storage);
157
+ const storageKey = options?.storageKey ?? DEFAULT_STORAGE_KEY;
158
+
159
+ let apps: CacheEntry<DataSourceApp[]> | null = null;
160
+ let dataSources: CacheEntry<DataSource[]> | null = null;
161
+ let users: CacheEntry<User[]> | null = null;
162
+ let brands: CacheEntry<Brand[]> | null = null;
163
+ let preferences: CacheEntry<TenantPreferences> | null = null;
164
+ const appConfigs = new Map<string, CacheEntry<AppConfig | null>>();
165
+ const userAppConfigs = new Map<string, CacheEntry<UserAppConfig | null>>();
166
+
167
+ let appsInFlight: Promise<DataSourceApp[]> | null = null;
168
+ let dataSourcesInFlight: Promise<DataSource[]> | null = null;
169
+ let usersInFlight: Promise<User[]> | null = null;
170
+ let brandsInFlight: Promise<Brand[]> | null = null;
171
+ let preferencesInFlight: Promise<TenantPreferences> | null = null;
172
+ const appConfigsInFlight = new Map<string, Promise<AppConfig | null>>();
173
+ const userAppConfigsInFlight = new Map<string, Promise<UserAppConfig | null>>();
174
+
175
+ /** Serialize the whole cache to storage. Best-effort — quota/serialization errors are swallowed. */
176
+ function persist(): void {
177
+ if (!storage) return;
178
+
179
+ const snapshot: InventorySnapshot = {
180
+ v: SNAPSHOT_VERSION,
181
+ apps,
182
+ dataSources,
183
+ users,
184
+ brands,
185
+ preferences,
186
+ appConfigs: [...appConfigs],
187
+ userAppConfigs: [...userAppConfigs]
188
+ };
189
+
190
+ try {
191
+ storage.setItem(storageKey, JSON.stringify(snapshot));
192
+ } catch {
193
+ /*
194
+ * Quota exceeded / serialization failure / storage revoked mid-session:
195
+ * keep the in-memory cache authoritative and carry on.
196
+ */
197
+ }
198
+ }
199
+
200
+ /** Populate the in-memory cache from a persisted snapshot, if one is present and current. */
201
+ function hydrate(): void {
202
+ if (!storage) return;
203
+
204
+ let raw: string | null;
205
+
206
+ try {
207
+ raw = storage.getItem(storageKey);
208
+ } catch {
209
+ return;
210
+ }
211
+
212
+ if (!raw) return;
213
+
214
+ let snapshot: InventorySnapshot | null = null;
215
+
216
+ try {
217
+ const parsed = JSON.parse(raw) as InventorySnapshot;
218
+
219
+ if (parsed && parsed.v === SNAPSHOT_VERSION) snapshot = parsed;
220
+ } catch {
221
+ snapshot = null;
222
+ }
223
+
224
+ if (!snapshot) return;
225
+
226
+ apps = snapshot.apps ?? null;
227
+ dataSources = snapshot.dataSources ?? null;
228
+ users = snapshot.users ?? null;
229
+ brands = snapshot.brands ?? null;
230
+ preferences = snapshot.preferences ?? null;
231
+
232
+ for (const [id, entry] of snapshot.appConfigs ?? []) appConfigs.set(id, entry);
233
+ for (const [id, entry] of snapshot.userAppConfigs ?? []) userAppConfigs.set(id, entry);
234
+ }
235
+
236
+ hydrate();
237
+
238
+ function isFresh<T>(entry: CacheEntry<T> | null | undefined): entry is CacheEntry<T> {
239
+ if (!entry) return false;
240
+ if (!Number.isFinite(ttlMs)) return true;
241
+
242
+ return Date.now() - entry.fetchedAt < ttlMs;
243
+ }
244
+
245
+ async function listApps(): Promise<DataSourceApp[]> {
246
+ if (isFresh(apps)) return apps.data;
247
+ if (appsInFlight) return appsInFlight;
248
+
249
+ appsInFlight = (async () => {
250
+ try {
251
+ const data = unwrapEnvelope<DataSourceApp[]>(await client.get('/v1/apps'));
252
+
253
+ apps = { data, fetchedAt: Date.now() };
254
+ persist();
255
+
256
+ return data;
257
+ } finally {
258
+ appsInFlight = null;
259
+ }
260
+ })();
261
+
262
+ return appsInFlight;
263
+ }
264
+
265
+ async function listDataSources(): Promise<DataSource[]> {
266
+ if (isFresh(dataSources)) return dataSources.data;
267
+ if (dataSourcesInFlight) return dataSourcesInFlight;
268
+
269
+ dataSourcesInFlight = (async () => {
270
+ try {
271
+ const queryParams = dataSourcesExpand ? { expand: dataSourcesExpand } : undefined;
272
+ const raw = unwrapEnvelope<DataSource[]>(
273
+ await client.get('/v1/apps/data-sources', queryParams)
274
+ );
275
+ const data = raw.map(normalizeDataSource);
276
+
277
+ dataSources = { data, fetchedAt: Date.now() };
278
+ persist();
279
+
280
+ return data;
281
+ } finally {
282
+ dataSourcesInFlight = null;
283
+ }
284
+ })();
285
+
286
+ return dataSourcesInFlight;
287
+ }
288
+
289
+ async function listUsers(): Promise<User[]> {
290
+ if (isFresh(users)) return users.data;
291
+ if (usersInFlight) return usersInFlight;
292
+
293
+ usersInFlight = (async () => {
294
+ try {
295
+ const data = unwrapEnvelope<User[]>(await client.get('/v1/users'));
296
+
297
+ users = { data, fetchedAt: Date.now() };
298
+ persist();
299
+
300
+ return data;
301
+ } finally {
302
+ usersInFlight = null;
303
+ }
304
+ })();
305
+
306
+ return usersInFlight;
307
+ }
308
+
309
+ async function listBrands(): Promise<Brand[]> {
310
+ if (isFresh(brands)) return brands.data;
311
+ if (brandsInFlight) return brandsInFlight;
312
+
313
+ brandsInFlight = (async () => {
314
+ try {
315
+ const data = unwrapEnvelope<Brand[]>(await client.get('/v1/tenant/brands'));
316
+
317
+ brands = { data, fetchedAt: Date.now() };
318
+ persist();
319
+
320
+ return data;
321
+ } finally {
322
+ brandsInFlight = null;
323
+ }
324
+ })();
325
+
326
+ return brandsInFlight;
327
+ }
328
+
329
+ async function getPreferences(): Promise<TenantPreferences> {
330
+ if (isFresh(preferences)) return preferences.data;
331
+ if (preferencesInFlight) return preferencesInFlight;
332
+
333
+ preferencesInFlight = (async () => {
334
+ try {
335
+ const data = unwrapEnvelope<TenantPreferences>(await client.get('/v1/tenant/preferences'));
336
+
337
+ preferences = { data, fetchedAt: Date.now() };
338
+ persist();
339
+
340
+ return data;
341
+ } finally {
342
+ preferencesInFlight = null;
343
+ }
344
+ })();
345
+
346
+ return preferencesInFlight;
347
+ }
348
+
349
+ async function getAppConfig(appId: string): Promise<AppConfig | null> {
350
+ return getConfig(appId, appConfigs, appConfigsInFlight, `/v1/tenant/apps/${appId}/config`);
351
+ }
352
+
353
+ async function getUserAppConfig(appId: string): Promise<UserAppConfig | null> {
354
+ return getConfig(appId, userAppConfigs, userAppConfigsInFlight, `/v1/tenant/apps/${appId}/user-config`);
355
+ }
356
+
357
+ function getConfig<T>(
358
+ appId: string,
359
+ cache: Map<string, CacheEntry<T | null>>,
360
+ inFlight: Map<string, Promise<T | null>>,
361
+ path: string
362
+ ): Promise<T | null> {
363
+ const cached = cache.get(appId);
364
+
365
+ if (isFresh(cached)) return Promise.resolve(cached.data);
366
+
367
+ const existing = inFlight.get(appId);
368
+
369
+ if (existing) return existing;
370
+
371
+ const promise = (async () => {
372
+ try {
373
+ const data = unwrapEnvelope<T>(await client.get(path));
374
+
375
+ cache.set(appId, { data, fetchedAt: Date.now() });
376
+ persist();
377
+
378
+ return data;
379
+ } catch (error) {
380
+ // A missing config is a valid empty state, not an error — cache the null.
381
+ if (isNotFound(error)) {
382
+ cache.set(appId, { data: null, fetchedAt: Date.now() });
383
+ persist();
384
+
385
+ return null;
386
+ }
387
+
388
+ throw error;
389
+ } finally {
390
+ inFlight.delete(appId);
391
+ }
392
+ })();
393
+
394
+ inFlight.set(appId, promise);
395
+
396
+ return promise;
397
+ }
398
+
399
+ async function listDataViews(params?: ListInventoryParams): Promise<DataView[]> {
400
+ const sources = await listDataSources();
401
+ const appIds = toIdSet(params?.appId);
402
+ const dataSourceIds = toIdSet(params?.dataSourceId);
403
+ const out: DataView[] = [];
404
+
405
+ for (const dataSource of sources) {
406
+ if (appIds && (dataSource.tenant_app_id == null || !appIds.has(dataSource.tenant_app_id))) continue;
407
+ if (dataSourceIds && !dataSourceIds.has(dataSource.id)) continue;
408
+ if (!dataSource.views) continue;
409
+
410
+ for (const view of dataSource.views) {
411
+ out.push(view);
412
+ }
413
+ }
414
+
415
+ return out;
416
+ }
417
+
418
+ async function listDataForms(params?: ListInventoryParams): Promise<DataForm[]> {
419
+ const sources = await listDataSources();
420
+ const appIds = toIdSet(params?.appId);
421
+ const dataSourceIds = toIdSet(params?.dataSourceId);
422
+ const out: DataForm[] = [];
423
+
424
+ for (const dataSource of sources) {
425
+ if (appIds && (dataSource.tenant_app_id == null || !appIds.has(dataSource.tenant_app_id))) continue;
426
+ if (dataSourceIds && !dataSourceIds.has(dataSource.id)) continue;
427
+ if (!dataSource.forms) continue;
428
+
429
+ for (const form of dataSource.forms) {
430
+ out.push(form);
431
+ }
432
+ }
433
+
434
+ return out;
435
+ }
436
+
437
+ function mutateCachedDataSources(mutator: (sources: DataSource[]) => DataSource[] | void): void {
438
+ if (!dataSources) return;
439
+
440
+ const next = mutator(dataSources.data);
441
+
442
+ if (next) {
443
+ dataSources = { data: next, fetchedAt: dataSources.fetchedAt };
444
+ persist();
445
+ }
446
+ }
447
+
448
+ function upsertDataView(view: DataView): void {
449
+ mutateCachedDataSources((sources) => {
450
+ const index = sources.findIndex(ds => ds.id === view.tenant_data_source_id);
451
+
452
+ if (index === -1) return;
453
+
454
+ const dataSource = sources[index];
455
+ const normalized = normalizeEmbeddedView(view);
456
+ const existingViews = dataSource.views ?? [];
457
+ const viewIndex = existingViews.findIndex(v => v.id === view.id);
458
+ const views = viewIndex === -1 ? [...existingViews, normalized] : existingViews.map((v, i) => (i === viewIndex ? normalized : v));
459
+ const next = [...sources];
460
+
461
+ next[index] = { ...dataSource, views };
462
+
463
+ return next;
464
+ });
465
+ }
466
+
467
+ function removeDataView(viewId: string): void {
468
+ mutateCachedDataSources((sources) => {
469
+ let touched = false;
470
+ const next = sources.map((dataSource) => {
471
+ if (!dataSource.views?.some(v => v.id === viewId)) return dataSource;
472
+
473
+ touched = true;
474
+
475
+ return { ...dataSource, views: dataSource.views.filter(v => v.id !== viewId) };
476
+ });
477
+
478
+ return touched ? next : undefined;
479
+ });
480
+ }
481
+
482
+ function upsertDataForm(form: DataForm): void {
483
+ mutateCachedDataSources((sources) => {
484
+ const index = sources.findIndex(ds => ds.id === form.tenant_data_source_id);
485
+
486
+ if (index === -1) return;
487
+
488
+ const dataSource = sources[index];
489
+ const normalized = normalizeEmbeddedForm(form as unknown as Record<string, unknown>, dataSource.id);
490
+ const existingForms = dataSource.forms ?? [];
491
+ const formIndex = existingForms.findIndex(f => f.id === form.id);
492
+ const forms = formIndex === -1 ? [...existingForms, normalized] : existingForms.map((f, i) => (i === formIndex ? normalized : f));
493
+ const next = [...sources];
494
+
495
+ next[index] = { ...dataSource, forms };
496
+
497
+ return next;
498
+ });
499
+ }
500
+
501
+ function removeDataForm(formId: string): void {
502
+ mutateCachedDataSources((sources) => {
503
+ let touched = false;
504
+ const next = sources.map((dataSource) => {
505
+ if (!dataSource.forms?.some(f => f.id === formId)) return dataSource;
506
+
507
+ touched = true;
508
+
509
+ return { ...dataSource, forms: dataSource.forms.filter(f => f.id !== formId) };
510
+ });
511
+
512
+ return touched ? next : undefined;
513
+ });
514
+ }
515
+
516
+ function invalidateApps(): void {
517
+ apps = null;
518
+ persist();
519
+ }
520
+
521
+ function invalidateDataSources(): void {
522
+ dataSources = null;
523
+ persist();
524
+ }
525
+
526
+ function invalidateUsers(): void {
527
+ users = null;
528
+ persist();
529
+ }
530
+
531
+ function invalidateBrands(): void {
532
+ brands = null;
533
+ persist();
534
+ }
535
+
536
+ function invalidatePreferences(): void {
537
+ preferences = null;
538
+ persist();
539
+ }
540
+
541
+ function invalidateAppConfig(appId?: string): void {
542
+ if (appId === undefined) appConfigs.clear();
543
+ else appConfigs.delete(appId);
544
+ persist();
545
+ }
546
+
547
+ function invalidateUserAppConfig(appId?: string): void {
548
+ if (appId === undefined) userAppConfigs.clear();
549
+ else userAppConfigs.delete(appId);
550
+ persist();
551
+ }
552
+
553
+ function upsertBrand(brand: Brand): void {
554
+ if (!brands) return;
555
+
556
+ const index = brands.data.findIndex(b => b.id === brand.id);
557
+ const data = index === -1 ? [...brands.data, brand] : brands.data.map((b, i) => (i === index ? brand : b));
558
+
559
+ brands = { data, fetchedAt: brands.fetchedAt };
560
+ persist();
561
+ }
562
+
563
+ function removeBrand(brandId: string): void {
564
+ if (!brands?.data.some(b => b.id === brandId)) return;
565
+
566
+ brands = { data: brands.data.filter(b => b.id !== brandId), fetchedAt: brands.fetchedAt };
567
+ persist();
568
+ }
569
+
570
+ function setAppConfig(appId: string, config: AppConfig | null): void {
571
+ appConfigs.set(appId, { data: config, fetchedAt: Date.now() });
572
+ persist();
573
+ }
574
+
575
+ function setUserAppConfig(appId: string, config: UserAppConfig | null): void {
576
+ userAppConfigs.set(appId, { data: config, fetchedAt: Date.now() });
577
+ persist();
578
+ }
579
+
580
+ async function refresh(): Promise<void> {
581
+ invalidateApps();
582
+ invalidateDataSources();
583
+ invalidateUsers();
584
+ invalidateBrands();
585
+ invalidatePreferences();
586
+ invalidateAppConfig();
587
+ invalidateUserAppConfig();
588
+ await Promise.all([listApps(), listDataSources()]);
589
+ }
590
+
591
+ const singletonLoaders: Record<
592
+ Exclude<InventoryLoadStepId, 'app-config' | 'user-app-config'>,
593
+ { message: string; run: () => Promise<unknown> }
594
+ > = {
595
+ apps: { message: 'Loading apps…', run: listApps },
596
+ 'data-sources': { message: 'Loading data sources…', run: listDataSources },
597
+ users: { message: 'Loading users…', run: listUsers },
598
+ brands: { message: 'Loading brands…', run: listBrands },
599
+ preferences: { message: 'Loading preferences…', run: getPreferences }
600
+ };
601
+
602
+ function mapToRecord<T>(map: Map<string, CacheEntry<T | null>>): Record<string, T | null> {
603
+ const out: Record<string, T | null> = {};
604
+
605
+ for (const [key, entry] of map) out[key] = entry.data;
606
+
607
+ return out;
608
+ }
609
+
610
+ function buildLoadResult(): InventoryLoadResult {
611
+ return {
612
+ apps: apps?.data ?? [],
613
+ dataSources: dataSources?.data ?? [],
614
+ users: users?.data ?? [],
615
+ brands: brands?.data ?? [],
616
+ preferences: preferences?.data ?? {},
617
+ appConfigs: mapToRecord(appConfigs),
618
+ userAppConfigs: mapToRecord(userAppConfigs)
619
+ };
620
+ }
621
+
622
+ async function load(loadOptions?: InventoryLoadOptions): Promise<InventoryLoadResult> {
623
+ const onProgress = loadOptions?.onProgress;
624
+ const force = loadOptions?.force ?? true;
625
+ const include = loadOptions?.include ?? DEFAULT_LOAD_STEPS;
626
+ /*
627
+ * Explicit `configAppIds` wins; otherwise default to the current app from
628
+ * VITE_APP_ID (no per-app config is warmed when that env var is unset).
629
+ */
630
+ const envAppId = readAppIdFromEnv();
631
+ const configAppIds = loadOptions?.configAppIds ?? (envAppId ? [envAppId] : []);
632
+
633
+ const steps: Array<{
634
+ id: InventoryLoadStepId; appId?: string; message: string; run: () => Promise<unknown>;
635
+ }> = [];
636
+
637
+ for (const id of include) {
638
+ if (id === 'app-config' || id === 'user-app-config') continue;
639
+
640
+ steps.push({ id, message: singletonLoaders[id].message, run: singletonLoaders[id].run });
641
+ }
642
+
643
+ for (const appId of configAppIds) {
644
+ steps.push({
645
+ id: 'app-config', appId, message: 'Loading app config…', run: () => getAppConfig(appId)
646
+ });
647
+ steps.push({
648
+ id: 'user-app-config', appId, message: 'Loading user app config…', run: () => getUserAppConfig(appId)
649
+ });
650
+ }
651
+
652
+ if (force) {
653
+ if (include.includes('apps')) invalidateApps();
654
+ if (include.includes('data-sources')) invalidateDataSources();
655
+ if (include.includes('users')) invalidateUsers();
656
+ if (include.includes('brands')) invalidateBrands();
657
+ if (include.includes('preferences')) invalidatePreferences();
658
+
659
+ for (const appId of configAppIds) {
660
+ invalidateAppConfig(appId);
661
+ invalidateUserAppConfig(appId);
662
+ }
663
+ }
664
+
665
+ const total = steps.length;
666
+
667
+ for (let index = 0; index < total; index++) {
668
+ const step = steps[index];
669
+ const current = index + 1;
670
+
671
+ onProgress?.({
672
+ step: step.id, appId: step.appId, message: step.message, current, total, ratio: index / total, phase: 'start'
673
+ });
674
+
675
+ try {
676
+ await step.run();
677
+ } catch (error) {
678
+ onProgress?.({
679
+ step: step.id, appId: step.appId, message: step.message, current, total, ratio: index / total, phase: 'error', error
680
+ });
681
+
682
+ throw error;
683
+ }
684
+
685
+ onProgress?.({
686
+ step: step.id, appId: step.appId, message: step.message, current, total, ratio: current / total, phase: 'success'
687
+ });
688
+ }
689
+
690
+ onProgress?.({
691
+ step: null, message: 'Ready', current: total, total, ratio: 1, phase: 'complete'
692
+ });
693
+
694
+ return buildLoadResult();
695
+ }
696
+
697
+ return {
698
+ listApps,
699
+ listDataSources,
700
+ listUsers,
701
+ listBrands,
702
+ getPreferences,
703
+ getAppConfig,
704
+ getUserAppConfig,
705
+ load,
706
+ listDataViews,
707
+ listDataForms,
708
+ refresh,
709
+ invalidateApps,
710
+ invalidateDataSources,
711
+ invalidateUsers,
712
+ invalidateBrands,
713
+ invalidatePreferences,
714
+ invalidateAppConfig,
715
+ invalidateUserAppConfig,
716
+ upsertDataView,
717
+ removeDataView,
718
+ upsertDataForm,
719
+ removeDataForm,
720
+ upsertBrand,
721
+ removeBrand,
722
+ setAppConfig,
723
+ setUserAppConfig
724
+ };
725
+ }